Read the entire file
File pi_digits.txt
# File pi_digits.txt 3.1415926535 8979323846 2643383279
The following program opens and reads the entire file and displays its contents on the screen:
with open("pi_digits.txt") as fileobject: contents = fileobject.read() print(contents) #Operation results 3.1415926535 8979323846 2643383279
Open the file with function open(), function open(0 accepts the name parameter of a file to be opened), and python finds the specified file in the directory where the file is currently executed. The function open() returns an object representing the file. This object is then saved in the variables that will be used later, or file handles. The keyword with closes the file without having to access it. In this program, we don't use close() to close the file, or we can do so, but if there is a bug in the program that causes the close() statement not to execute, the file will not close. With the object representing the file pi_digits, we can use the method read() to read the content and store it as a long string in the variable contents.
File path
Relative paths: paths to the current directory
In linux:
with open('text_files/filename.txt') as file_object:
In Windows:
with open('text_files\filename.txt') as file_object:
Absolute path: relative to the root directory
In linux:
file_path = '/home/ehmatthes/other_files/text_files/filename.txt' with open(file_path) as file_object:
In Windows:
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt' with open(file_path) as file_object:
Create a list of lines in a file
When reading a file, it is often read line by line.
Method readlines() reads each line from a file and stores it in a list;
filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() print(lines) for line in lines: print(line.rstrip()) #Operation results ['3.1415926535\n', ' 8979323846\n', ' 2643383279\n'] 3.1415926535 8979323846 2643383279
Write empty files
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.\n")
Operation results:
If a file exists, write is overwritten and write is created if it does not exist.
In this example, two arguments are provided when calling open() (see bah). The first argument is also the name of the file to open; the second argument ('w') tells Python that we want to open the file in write mode. When opening a file, you can specify read mode ('r'), write mode ('w'), add mode ('a') or mode ('r+') that allows you to read and write files. If you omit the mode argument, Python will open the file in the default read-only mode.I love programming.
Attached to the document
filename = 'programming.txt' with open(filename,'a') as file_object: file_object.write("I also love python!\n") file_object.write("I love creating apps\n")
# Operation results
Add at the end of the file
I love programming.
I also love python!
I love creating apps
Handling exceptions
First look at a simple exception:print(5/0) #Operation results Traceback (most recent call last): File "D:/python_cd/<Python Programming from Introduction to Practice/division.py", line 1, in <module> print(5/0) ZeroDivisionError: division by zero
Obviously python can't do this, so you'll see a traceback that points out that the error ZeroDivision Error is an exception object, so python will stop running the program. Now we'll tell python what to do when such an error occurs, instead of terminating the program to return an error.
try: print(5/0) except: print("You can't divide by zero!") #Operation results You can't divide by zero!
In this example, the code in the try code block causes a ZeroDivision Error exception, so Python points out how to solve the problem of the except code block and runs the code in it. In this way, the user sees a friendly error message, not a traceback.
else code block
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: ") try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide by 0!") else: print(answer) #Operation results Give me two numbers, and I'll divide them. Enter 'q' to quit. First number: 12 Second number: 6 2.0 First number: 12 Second number: 0 You can't divide by 0!
The try-except-else code block works roughly as follows: Python tries to execute the code in the try code block; only code that may cause an exception needs to be placed in the try statement. Sometimes, there are code that needs to be run only when the try block is successfully executed; the code should be placed in the else block. The except code block tells Python what to do if it raises a specified exception when it tries to run the code in the try code block. There is a pass statement in python, which can be used in the code block to make Python not to do, such as adding pass only under the except statement to indicate that the error is not returned.
JSON module
The module JSON allows you to dump a simple Python data structure into a file and load the data in that file when the program runs again. You can also use JSON to share data between Python programs. More importantly, JSON data formats are not Python-specific, which allows you to share data stored in JSON formats with people using other programming languages. This is a portable format, very useful and easy to learn.
import json info={'name':'Tom', 'age':'12', 'job':'work',} f=open('file1.txt','w') f.write(json.dumps(info)) f.close()
json.loads
import json f=open('file1.txt','r') data=json.loads(f.read()) f.close() print(data) print(data['name'])