Code examples python syntax: file reading and writing

Keywords: Python Pycharm

	in use python When programming, we often encounter the operation of reading and writing files. Many children's shoes are perplexed by various modes of reading and writing files (such as reading, writing, adding, etc.) and unclear open,read,readline,readlines,write And other methods. File read / write yes python Basic operation, this paper briefly studies from examples, and presents the differences of code implementation.

1. Opening and closing of files: open function and close function

1.1 open function

If you want to use python to read files (such as txt, csv, etc.), the first step is to open the file with the open function. open() is a built-in function of python. It will return a file object with read, readline, write, close and other methods. The open function has two parameters:

fo = open('file','mode')

Parameter interpretation
File: the path of the file to be opened
Mode (optional): open the mode of the file, such as read-only, append, write, etc

mode common modes:
r: Indicates that the file can only be read
w: Indicates that the file can only be written
a: Means to open a file, add content to the original content, and write at the end
w +: indicates that the file can be read and written

When you need to read and write files in bytes (binary), just add 'b' to the mode parameter:
rb: open a file in binary format for read-only
wb: open a file in binary format for write only
ab: open a file in binary format for appending
wb +: open a file in binary format for reading and writing

When you read a text file in the default mode (binary files cannot), the newline character in the file will be converted to '\ n' form.

1.2 close function

The close () method of the File object flushes any information that has not been written in the buffer and closes the File. After that, it can no longer be written. When a reference to a File object is reassigned to another File, Python closes the previous File. It is a good habit to close files with the close () method.
Examples are as follows:

# Open a file
fo = open("foo.txt", "w")
print("file name: ", fo.name)
 
# Close open files
fo.close()

1.3 with statement

When opening a file, many people usually use open('File ') directly, which is not cool. It is best to use the with keyword. The advantage is that the file will be closed correctly when the sub sentence is finished, even if an exception is thrown at some time.
example:

with open('workfile') as f:
     read_data = f.read()
f.closed

This is a file opening method for exception handling. (does it seem more compelling? haha)

2. FILE object

After a file is opened, you have a file object fo, and you can get all kinds of information about the file. The following is a list of all properties related to the file object:

attributedescribe
file.closeClose the file. If closed, return True
file.modeReturns the open mode of the file
file.nameReturns the name of the file

Examples are as follows:

# Open a file
fo = open("foo.txt", "w")
print("file name: ", fo.name)
print("Is it closed : ", fo.closed)
print("Access mode : ", fo.mode)

The example output results are as follows:

file name:  foo.txt
 Is it closed :  False
 Access mode :  w

3. There are three ways to read file objects: read(), readline(), and readlines()

The following is an example of reading a csv file. The contents of csv are as follows:

Frog
FrogDogShadowDiversion
1m3m2m1m
2m4m2m5m
4m7m6m6m
9m8m6m8m
1p1p3p8m

3.1 read() function

When you open a file with the open function, you can use various methods of the file object. read() reads some data and returns it as a string (in text mode) or a byte object (in binary mode).

read() has one parameter:

#The parameter size (optional) is a number, indicating the byte count read from the open file. By default, it reads all.
fo.read(size) # fo is a file object

Read the first 66 bytes of the above csv file as follows:

fo = open("f:\\test.csv","r")
content = fo.read(66)
print(content)
fo.close()

The output result is:

Frog,,,
Frog,Dog,Shadow,Diversion
1m,3m,2m,1m
2m,4m,2m,5m
4m,7m,6m

Note that the bytes here contain line breaks at the end of each line. Spaces do not occupy the byte position.

3.2 readline() function

The readLine method reads the entire line from the file, including the newline '\ n'. The newline (\ n) is left at the end of the string. If the file does not end with a newline, it is omitted from the last line of the file, making the return value unambiguous. If f.readline() If an empty string is returned, it indicates that the end of the file has been reached, while the empty line is represented by '\ n', and the string contains only one newline character.
f.readline() has one parameter: f.readline(size), where size represents the number of bytes read from the file.
Take the above csv file as an example.

with  open('f:\\test.csv') as f:
    print(f.readline())
    print(f.readline(13))
    f.close()

The output result is:

Frog,,,

Frog,Dog,Shad

It can be seen that the readline method will remember the position read by the previous readline function and then read the next line. Therefore, when you need to traverse each line of the file, you might as well use the readline method!

3.3 readlines() function

The readlines method looks like the readline method, but its functions are different. As mentioned earlier, the readline method reads only one row, while the readlines method reads all rows and returns a list composed of all rows. The readlines method has no parameters and is easier to use.

with  open('f:\\test.csv') as f:
    print(f.readlines())
    f.close()

The output result is:

['Frog,,,\n', 'Frog,Dog,Shadow,Diversion\n', '1m,3m,2m,1m\n', '2m,4m,2m,5m\n', '4m,7m,6m,6m\n', '9m,8m,6m,8m\n', '1p,1p,3p,8m\n']

The newline character of each line in the csv file is displayed, and each line is a string. Further line processing is carried out. Examples are as follows:

with open('f:\\test.csv') as fo:
     for line in fo.readlines():
         line = line.strip()  # Remove newline
         data = line.split(',') # To split the slice into multiple small strings
         print("data",data)

Get the processing results of each line:

data ['Frog', '', '', '']
data ['Frog', 'Dog', 'Shadow', 'Diversion']
data ['1m', '3m', '2m', '1m']
data ['2m', '4m', '2m', '5m']
data ['4m', '7m', '6m', '6m']
data ['9m', '8m', '6m', '8m']
data ['1p', '1p', '3p', '8m']

4. Write operation of file object: write()

The write method, as its name suggests, writes a string to a file.

with  open('sample.txt','w') as fw:
    fw.write('hello,my friends!\nthis is python big data analysis')
    fw.close()

Posted by ashbai on Tue, 09 Nov 2021 23:53:07 -0800