Python study notes the fourth day

File reading and writing

1. The open function is used to open the file with the specified path in the current directory and store it in the file_object variable;
2. The keyword with will automatically close the file after it does not need to access the file'readme.txt' (you can also Call the close method to close the file directly, but it is generally recommended to let python choose the right time to close it, so as to avoid
data damage due to improperly closing the file);
3. If you need to read a file anywhere in the system, then Need to use absolute path (windows system sometimes cannot interpret the slash in the path normally, then the path should be specified in the original string, that is, add r before the path single quotation mark); 4. fileinput.input(filename) method can also be used Open the file, but it is generally recommended to use the open function to open the file, which has better execution efficiency and stability.
5. The first argument is also the name of the file to be opened; the second argument ('w') tells Python that we want to open the file in write mode. When opening a file, you can specify the read mode ('r'), write mode ('w'), append mode ('a') or allow you to read and write files Mode ('r+'). If you omit the mode argument, Python will open the file in the default read-only mode.
**Note:** When printing the contents of the file, a blank line is added at the end of each line of text. This is because the print() method also comes with a line break after the line break of each line of text. You can use rstrip() Method, or end=''parameter to solve
this problem.

Use readlines() method to read line by line

filename = „readme.txt‟
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line, end=„‟)
Note: Use the readlines method to read the contents of the file first. Stored
in a list, then the file will be automatically closed (to protect the
contents of the file ); the readlines() method can also identify all legal line breaks.

Use the readline() method to read line by line

In addition to the readlines() method, you can also use the readline([n]) method to
read data line by line, and specify the number of characters to read. If
somefile.readline() returns'Hello, world!\n', then
somefile.readline(5) will return'Hello'.

Use the read() method to read the file

The read([n]) method is used to read the content of the entire file. If the parameter n
is given, the first n characters or byte stream content are read.

Use write() method to write data

The function write() does not add a newline character at the end of the text you write, so if you do not specify a newline character when writing multiple lines, the file may not look what you want

#创建一个包含文件各行内容的列表
filename=r"C:\Users\zhouyi\Desktop\pi_digits.txt"
with open(filename) as file_object:
     lines=file_object.readlines()
print(lines)

#写入空文件
file_name='a.txt'
with open(file_name,'r+') as file_object:
     file_object.write("I love programming2")
with open(file_name,'r') as file_object:
     lines=file_object.readlines()
print(lines)

abnormal

Exceptions are handled using try-except code blocks. The try-except code block allows Python to perform the specified operation and tells Python what to do when an exception occurs. The working principle of the try-except-else code block is roughly as follows: Python tries to execute the code in the try code block; only the code that may cause an exception needs to be placed in the try statement. Sometimes, there are codes that need to be run only when the try code block is successfully executed; these codes should be placed in the else code block. Finally, the code must be executed.

# 将文件读取定义成一个函数
def readFun(file_name):
    try:
        with open(file_name, "r") as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        print("文件未找到")
    else:
        print('此函数运行成功')
    finally:
        return contents
            
contents=readFun("a.txt")
print(contents)

json data storage

In python, the module json provides a simple way to access data, and it is convenient to share these data with other programs. The json (JavaScript Object Notation) format was originally developed for the JavaScript language. It is a common lightweight data format and is adopted by many languages ​​including python. It uses key-value pairs for data storage: "key": "value" #Key-value pairs are stored in double quotes. The data file extension in json format is .json.

Guess you like

Origin blog.csdn.net/qq_44788518/article/details/108614228