Detailed explanation of python reading and writing files, writing data to a file or reading a file and writing it to another file.

        

Table of contents

 Practice 1: read and print the file, read()

 Practice 2: Read a line of the file and print it, readline()

 Practice 3: Read all the lines of the file and store them in a list and print them, readlines()

 Practice 4: Write a string to a file, write()

 Practice 5: Write the contents of one file to another file line by line


        Python's read and write file operations will be encountered in many projects, so take the time to summarize this part in case you need it.

        When reading and writing with python, commonly used methods are generally involved, such as open, write, read, readline, readlines, with, etc. Next, analyze these methods, and then use these methods through practice.

open(filename,mode):

        This function is a built-in function of python. Open a file through this function. The name or path of the file is filename; while opening the file, you can declare the parameter mode to specify whether the file is read-only or write-only or readable and writable, etc. , the default is read-only; the return value of this function is a file object, and a series of methods such as write and read can be called through the file object.

Parameter mode: The value of this parameter can be the following values

r: Open the file as read-only. The file pointer will be placed at the beginning of the file. The default value for this parameter.

w: Only write to this file, that is, only write to this file. If the file already exists, the file will be opened and edited from the beginning, ie the original content will be deleted. If the file does not exist, a new file is created.

r+: Open a file for reading and writing. The file pointer will be placed at the beginning of the file.

w+: Open a file for reading and writing. If the file already exists, the file will be opened and edited from the beginning, ie the original content will be deleted. If the file does not exist, create a new file. The difference from w is that it can read

a: Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, a new file is created for writing.

a+: Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be opened in append mode. If the file does not exist, create a new file for reading and writing.

In addition, you can add an additional b, namely rb, wb, rb+, wb+, ab, ab+, these mean that the way to open the file is to open it in binary form, and the others are consistent.

         By calling the function open(), we get a file object, through which the following methods can be called:

read([size]) : size indicates the number of bytes read from the file, if size is not specified, the entire file will be returned, and read() will return "" (empty string) when it reaches the end of the file.

readline() : This method reads the entire line from the file, including the newline character '\n'.

readlines([size])  : Returns a list containing size lines, if size is not specified, returns all lines, that is, reads all lines, and puts all lines into a list, each line as a string, one in the list An element represents a row.

write("context\n") : The content inside the double quotes is the content to be written into the file. Make sure it is a string. If you want to write data other than a string, convert it to a string before writing enter.

close():  Close the file. After the file is opened and processed, the file needs to be closed. If you use with open() as .. you don't need to call the close method.

 Practice 1: read and print the file, read()

Create a txt file, save the following content, notice that I don't have a line break after aaa:

ddddd
bbb
ccc
aaa

 Write the following code:

# 获得文件的路径
fpath1 = r"C:\Users\LBS\Desktop\test1.txt"
# 使用with open打开文件,这样不用调用close()方法来关闭文件了
with open(fpath1, 'r') as f:
    # read()方法,读取文件中所有的内容
    content = f.read()
    print(content)

 The result is as follows:

 

 Practice 2: Read a line of the file and print it, readline()

# 获得文件的路径
fpath1 = r"C:\Users\LBS\Desktop\test1.txt"
# 使用with open打开文件,这样不用调用close()方法来关闭文件了
with open(fpath1, 'r') as f:
    # readline()方法,读取文件中每一行,当读取完一行再次读取时,则从上次读取结束处开始读取
    content1 = f.readline()
    print(content1)
    content2 = f.readline()
    print(content2)

 The result is as follows: 

 Practice 3: Read all the lines of the file and store them in a list and print them, readlines()

# 获得文件的路径
fpath1 = r"C:\Users\LBS\Desktop\test1.txt"
# 使用with open打开文件,这样不用调用close()方法来关闭文件了
with open(fpath1, 'r') as f:
    # readlines()方法,读取文件中所有行,每一行作为一个字符串存入在列表中,并且换行符用\n来表示。
    content = f.readlines()
    print(content)

 The result is as follows: 

 Practice 4: Write a string to a file, write()

 Note that when I open the file here, the parameter in me becomes w, and w means that I clear all the content in the file every time and then write.

Write the code as follows:

# 获得文件的路径
fpath1 = r"C:\Users\LBS\Desktop\test1.txt"
# 使用with open打开文件,这样不用调用close()方法来关闭文件了
with open(fpath1, 'w') as f:
    # readlines()方法,读取文件中所有行,每一行作为一个字符串存入在列表中,并且换行符用\n来表示。
    content = f.write('eeeee\n')

The result is as follows: the previous content is cleared, and only the written content is stored. If you want to write after the previous content, replace the parameter in open with 'a' or 'a+'

 Practice 5: Write the contents of one file to another file line by line

Suppose there are currently two txt files, the contents are as follows:

 We intend to write the contents of the aaa.txt file into test1, and ensure that the original contents of test1 will not be deleted.

Write the following code:

# 获得两个文件的路径
fpath1 = r"C:\Users\LBS\Desktop\aaa.txt"
fpath2 = r"C:\Users\LBS\Desktop\test1.txt"
# 以只读的形式打开文件fpath1
with open(fpath1, 'r') as f:
    # readlines()方法,读取文件中所有行,每一行作为一个字符串存入在列表中,并且换行符用\n来表示。
    # 这样我们得到了一个字符串列表,字符串列表中的每个元素代表一行内容
    aaa_content = f.readlines()
    # 以列表的形式打印aaa.txt中的内容
    print('aaa.txt中的内容为:{}'.format(aaa_content))
    # 以追加的形式打开文件fpath2
    with open(fpath2, 'a+') as f1:
        # 循环遍历aaa.txt中每一行的内容,写入文件遇到\n时自动换行
        for i in aaa_content:
            f1.write(i)

The result is: It can be seen that four lines of content are added after eeeee

 The above is the application of python to read and write files. You can try the following when the open file mode in open is changed. What is the difference?

Writing is not easy, please indicate the source for reprinting.

Guess you like

Origin blog.csdn.net/BaoITcore/article/details/127225147