- Reading from a file
from pathlib import Path
path = Path('pi_digits.txt')
contents = path.read_text()
print(contents)
Use Python Library called pathlib
Import path class
Assign variable to the object representing the file 'pi_digits.txt'
Since this file is saved in the same directory as the .py file we’re writing, the filename is all that Path needs to access the file.
Use read_text() method on the variable to read the entire contents of the file
Print it by giving another variable for this method to work on the object specified
Use contents = path.read_text().rstrip() to remove the blank space of the output because read_text() method returns empty string when it reaches the end of the content in a file
This is called method chaining
- Reading a file stored in different directory
path = Path('/home/eric/data_files/text_files/filename.txt')
It is an absolute file path
relative file path can only be used if the file you want to run on your program file
is stored in the subset of the directory where your program file is stored
*Windows systems use a backslash (\) instead of a
forward slash (/) when displaying file paths, but you
should use forward slashes in your code, even on
Windows. The pathlib library will automatically use the
correct representation of the path when it interacts
with your system, or any user’s system.
- Accessing a file's lines
- You can use the splitlines() method to turn a long single string
into a set of lines, and then use a for loop to examine each
line from a file, one at a time - for example:
lines = contents.splitlines()
for line in lines:
print(line)
- Working with a File's contents
- First, we’ll attempt to build a single
string containing all the digits in the file with no whitespace in it:
from pathlib import Path
path = Path('pi_digits.txt')
contents = path.read_text()
lines = contents.splitlines()
pi_string = ''
for line in lines:
pi_string += line
print(pi_string)
print(len(pi_string))
1.pi_string is a variable used to make a single list
2.using for loop, all the lines that have been split and returned by contents.splitlines(), will be added into the single list named pi_string
3.print the list and print the length of the list
3.1415926535 8979323846 2643383279
36
we should remove the whitespaces created when lines were split and returned
--snip--
for line in lines:
pi_string += line.lstrip()
print(pi_string)
print(len(pi_string))
3.141592653589793238462643383279
32
Accurate output was given. 32 digits in the content of the file.
Note that:
When Python reads from a text file, it interprets all
text in the file as a string. If you read in a number and
want to work with that value in a numerical context,
you’ll have to convert it to an integer using the int()
function or a float using the float() function.
replace() method to replace a value in a string with another value
You can skip the
temporary variable and loop directly over the list that splitlines() returns:
for line in contents.splitlines():
Remove the temporary variable from each of the programs in this section,
to make them more concise.
- Writing to a file
from pathlib import Path
contents = "I love programming.\n"
contents += "I love creating new games.\n"
path = Path('programming.txt')
path.write_text(contents)
Use write_text method with the parenthesis defined.
The text file content will be changed once you run this code.
Python can only write strings to a text file. If you want
to store numerical data in a text file, you’ll have to
convert the data to string format first using the str()
function. No list, or tuples. Only strings.
The write_text() method does a few things behind the
scenes. If the file that path points to doesn’t exist, it creates
that file.
Be careful when calling write_text() on a path object.
If the file already exists, write_text() will erase the
current contents of the file and write new contents to
the file.
- ZeroDivisionError Exception
- The codeblock below is a simple division calculator
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
answer = int(first_number) / int(second_number)
print(answer)
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
If the code in a try block works, Python skips over
the except block. If the code in the try block causes an error,
Python looks for an except block whose error matches the
one that was raised, and runs the code in that block.
*Pyhton always automatically executes the method that returns value even if its assigned to a variable in the first place
- FileNotFoundError Exception
- It’s often best to start at the very end of the traceback. This is important
because it tells us what kind of exception to use in the
except block that we’ll write.
path = Path('alice.txt')
try:
contents = path.read_text(encoding='utf-8')
except FileNotFoundError:
print(f"Sorry, the file {path} does not exist.")
The encoding argument is
needed when your system’s default encoding doesn’t match
the encoding of the file that’s being read. This is most likely
to happen when reading from a file that wasn’t created on
your system.
- Analyzing Text
- split() method, which by default splits a string
wherever it finds any whitespace
To make a program fail silently, you write
a try block as usual, but you explicitly tell Python to do
nothing in the except block. Python has a pass statement that
tells it to do nothing in a block:
try:
--snip--
except FileNotFoundError:
pass
else:
--snip--
- Storing Data
- A simple way to do this
involves storing your data using the json module. - The json module allows you to convert simple Python data
structures into JSON-formatted strings, and then load the
data from that file the next time the program runs. You can
also use json to share data between different Python
programs.
Using json.dumps() and json.loads()
from pathlib import Path
import json
numbers = [2, 3, 5, 7, 11, 13]
path = Path('numbers.json')
contents = json.dumps(numbers)
path.write_text(contents)
1. import json 2. give a name to the file in .json 3. use json.dumps() method to convert the data 4. write the data into the file using .write_text() 5. Run the code
from pathlib import Path
import json
path = Path('numbers.json')
contents = path.read_text()
numbers = json.loads(contents)
print(numbers)
1. import json 2. read the file using read_text() 3. convert the data using json.loads() method 4. Print the data as ouput
- Refactoring
you’ll recognize that you could improve the code by
breaking it up into a series of functions that have specific
jobs. This process is called refactoring. Refactoring makes
your code cleaner, easier to understand, and easier to
extend.
*There are many helpful methods you can use with Path
objects. The exists() method returns True if a file or folder
exists and False if it doesn’t.
* The return statement can be used as a period marker for if statement running within a function. So there's no need to write else: statement if you have a code that is running after when the codes within the if statement fails
'Python > Python Crash Course' 카테고리의 다른 글
Python Crash Course: 챕터 11 (0) | 2024.07.12 |
---|---|
Python Crash Course: 챕터 9 (0) | 2024.07.01 |
Python Crash Course: 챕터 8 (1) | 2024.07.01 |
Python Crash Course: 챕터 7 (0) | 2024.06.29 |
Python Crash Course: 챕터 6 (0) | 2024.06.28 |