Logo Passei Direto
Buscar
Material
páginas com resultados encontrados.
páginas com resultados encontrados.
left-side-bubbles-backgroundright-side-bubbles-background

Crie sua conta grátis para liberar esse material. 🤩

Já tem uma conta?

Ao continuar, você aceita os Termos de Uso e Política de Privacidade

left-side-bubbles-backgroundright-side-bubbles-background

Crie sua conta grátis para liberar esse material. 🤩

Já tem uma conta?

Ao continuar, você aceita os Termos de Uso e Política de Privacidade

left-side-bubbles-backgroundright-side-bubbles-background

Crie sua conta grátis para liberar esse material. 🤩

Já tem uma conta?

Ao continuar, você aceita os Termos de Uso e Política de Privacidade

left-side-bubbles-backgroundright-side-bubbles-background

Crie sua conta grátis para liberar esse material. 🤩

Já tem uma conta?

Ao continuar, você aceita os Termos de Uso e Política de Privacidade

left-side-bubbles-backgroundright-side-bubbles-background

Crie sua conta grátis para liberar esse material. 🤩

Já tem uma conta?

Ao continuar, você aceita os Termos de Uso e Política de Privacidade

Prévia do material em texto

Operating
System
File location open() function example
Mac /users/student/ fileobj = open("/users/student/output.txt")
Linux /usr/code/ fileobj = open("/usr/code/output.txt")
Windows
c:\projects\
code\
fileobj = open("c:/projects/code/output.txt")
or
fileobj =
open("c:\\projects\\code\\output.txt")
Table 14.2 Opening files on different paths. In each of the following cases, a file called output.txt is located in a different folder
than the Python folder. Windows uses backslash \ characters instead of forward slash / characters for the path. If the backslash is
included directly in open(), then an additional backslash is needed for Python to understand the location correctly.
CONCEPTS IN PRACTICE
Opening files at different locations
For each question, assume that the Python file executing the open() function is not in the same folder as
the out.txt file.
Each question indicates the location of out.txt, the type of computer, and the desired mode for opening the
file. Choose which option is best for opening out.txt.
1. /users/turtle/files on a Mac for reading
a. fileobj = open("out.txt")
b. fileobj = open("/users/turtle/files/out.txt")
c. fileobj = open("/users/turtle/files/out.txt", 'w')
2. c:\documents\ on a Windows computer for reading
a. fileobj = open("out.txt")
b. fileobj = open("c:/documents/out.txt", 'a')
c. fileobj = open("c:/documents/out.txt")
3. /users/turtle/logs on a Linux computer for writing
a. fileobj = open("out.txt")
b. fileobj = open("/users/turtle/logs/out.txt")
c. fileobj = open("/users/turtle/logs/out.txt", 'w')
4. c:\proj\assets on a Windows computer in append mode
a. fileobj = open("c:\\proj\\assets\\out.txt", 'a')
b. fileobj = open("c:\proj\assets\out.txt", 'a')
Working with CSV files
In Python, files are read from and written to as Unicode by default. Many common file formats use Unicode
336 14 • Files
Access for free at openstax.org
such as text files (.txt), Python code files (.py), and other code files (.c,.java).
Comma separated value (CSV, .csv) files are often used for storing tabular data. These files store cells of
information as Unicode separated by commas. CSV files can be read using methods learned thus far, as seen in
the example below.
Figure 14.2 CSV files. A CSV file is simply a text file with rows separated by newline \n characters and cells separated by commas.
Raw text of the file:
Title, Author, Pages\n1984, George Orwell, 268\nJane Eyre, Charlotte Bronte,
532\nWalden, Henry David Thoreau, 156\nMoby Dick, Herman Melville, 538
EXAMPLE 14.3
Processing a CSV file
"""Processing a CSV file."""
# Open the CSV file for reading
file_obj = open("books.csv")
# Rows are separated by newline \n characters, so readlines() can be used to
read in all rows into a string list
csv_rows = file_obj.readlines()
list_csv = []
# Remove \n characters from each row and split by comma and save into a 2D
structure
for row in csv_rows:
14.3 • Files in different locations and working with CSV files 337
# Remove \n character
row = row.strip("\n")
# Split using commas
cells = row.split(",")
list_csv.append(cells)
# Print result
print(list_csv)
The code's output is:
[['Title', ' Author', ' Pages'], ['1984', ' George Orwell', ' 268'], ['Jane
Eyre', ' Charlotte Bronte', ' 532'], ['Walden', ' Henry David Thoreau', ' 156'],
['Moby Dick', ' Herman Melville', ' 538']]
CONCEPTS IN PRACTICE
File types and CSV files
5. Why does readlines() work for reading the rows in a CSV file?
a. readlines() reads line by line using the newline \n character.
b. readlines() is not appropriate for reading a CSV file.
c. readlines() automatically recognizes a CSV file and works accordingly.
6. For the code in the example, what would be the output for the statement print(list_csv[1][2])?
a. 532
b. 268
c. Jane Eyre
7. What is the output of the following code for the books.csv seen above?
file_obj = open("books.csv")
csv_read = file_obj.readline()
print(csv_read)
a. ['Title, Author, Pages\n', '1984, George Orwell, 268\n', 'Jane Eyre,
Charlotte Bronte, 532\n', 'Walden, Henry David Thoreau, 156\n', 'Moby Dick,
Herman Melville, 538']
b. [['Title', ' Author', ' Pages'], ['1984', ' George Orwell', ' 268'], ['Jane
Eyre', ' Charlotte Bronte', ' 532'], ['Walden', ' Henry David Thoreau', '
156'], ['Moby Dick', ' Herman Melville', ' 538']]
c. Title, Author, Pages
338 14 • Files
Access for free at openstax.org
EXPLORING FURTHER
Files such as Word documents (.docx) and PDF documents (.pdf), image formats such as Portable Network
Graphics (PNG, .png) and Joint Photographic Experts Group (JPEG, .jpeg or .jpg) as well as many other file
types are encoded differently.
Some types of non-Unicode files can be read using specialized libraries that support the reading and writing
of different file types.
PyPDF (https://openstax.org/r/100readthedocs) is a popular library that can be used to extract information
from PDF files.
BeautifulSoup (https://openstax.org/r/100software) can be used to extract information from XML and HTML
files. XML and HTML files usually contain unicode with structure provided through the use of angled <>
bracket tags.
python-docx (https://openstax.org/r/100readwrtedocx) can be used to read and write DOCX files.
Additionally, csv (https://openstax.org/r/100csvlibrary) is a built-in library that can be used to extract
information from CSV files.
TRY IT
Processing a CSV file
The file fe.csv contains scores for a group of students on a final exam. Write a program to display the
average score.
Access multimedia content (https://openstax.org/books/introduction-python-programming/pages/
14-3-files-in-different-locations-and-working-with-csv-files)
14.4 Handling exceptions
Learning objectives
By the end of this section you should be able to
• Describe two exceptions that may occur when reading files.
• Write try/except statements that handle built-in exceptions.
Runtime errors
Various errors may occur when reading a file:
• FileNotFoundError: The filename or path is invalid.
• IndexError/ValueError: The file's format is invalid.
• Other errors caused by invalid contents of a file.
When an error occurs, the program terminates with an error message.
14.4 • Handling exceptions 339
https://openstax.org/r/100readthedocs
https://openstax.org/r/100software
https://openstax.org/r/100readwrtedocx
https://openstax.org/r/100csvlibrary
https://openstax.org/books/introduction-python-programming/pages/14-3-files-in-different-locations-and-working-with-csv-files
https://openstax.org/books/introduction-python-programming/pages/14-3-files-in-different-locations-and-working-with-csv-files
EXAMPLE 14.4
Typo in a file
A file named food_order.txt has the following contents:
5 sandwiches
4 chips
1 pickle
soft drinks
The following program expects each line of the file to begin with an integer:
for line in open("food_order.txt"):
space = line.index(" ")
qty = int(line[:space])
item = line[space+1:-1]
print(qty, item)
Unfortunately, the line "soft drinks" does not begin with an integer. As a result, the program terminates
and displays an error message:
Traceback (most recent call last):
File "food_order.py", line 3
qty = int(line[:space])
ValueError: invalid literal for int() with base 10: 'soft'
CONCEPTS IN PRACTICE
Common exceptions
What error might occur in each situation?
1. The line "soft drinks" is changed to "3-4 soft drinks".
a. FileNotFoundError
b. IndexError
c. ValueError
2. for line in open("food_order.text"):
a. FileNotFoundError
b. IndexError
c. ValueError
340 14 • Files
Access for free at openstax.org
	Chapter 14 Files
	14.4 Handling exceptions

Mais conteúdos dessa disciplina