Python file operation

Keywords: Python Pycharm

1, Create and open files

open() method
The open() method is used to open a file and return the file object. This function is required during file processing. If the file cannot be opened, OSError will be thrown.
Note: when using the open() method, be sure to close the file object, that is, call the close() method.
The common form of the open() function is to receive two parameters: file and mode.
file = open(file,mode)
Full syntax format:
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
Parameter Description:

  • File: file path (relative or absolute)
  • Mode: optional parameter, which specifies the file opening mode. The default is read-only (i.e. r)
  • Buffering: an optional parameter that specifies the buffering mode of read-write files. A value of 0 means no caching; A value of 1 indicates the cache, and if greater than 1 indicates the cache size. The default is cache mode
  • Encoding: file encoding format, usually utf-8
  • errors: error level
  • newline: distinguish line breaks
  • closefd: type of file parameter passed in

Description of mode parameter:

patternexplainbe careful
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. Default modeFile must exist
rbOpen a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. It is generally used for non text files, such as pictures.File must exist
r+Open the file for reading and writing. The file pointer will be placed at the beginning of the file, and writing will overwrite the original content againFile must exist
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. It is generally used for non text files, such as pictures.File must exist
wOpen files in write only mode; If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.If the file exists, the file contents are overwritten, otherwise a new file is created
wbOpen the file in binary format and use write only mode. It is generally used for non text files, such as pictures, audio, etcIf the file exists, the file contents are overwritten, otherwise a new file is created
w+After opening the file, empty the contents of the file to make it an empty file with read-write permissionIf the file exists, the file contents are overwritten, otherwise a new file is created
wb+Open a file in binary format for reading and writing. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted.If the file exists, the file contents are overwritten, otherwise a new file is created
aOpen the file in append mode. If the file already exists, the file pointer will be placed at the end of the file (the new content will be written after the existing content). Otherwise, a file will be created for writing.
abOpen the file in binary format and adopt append mode. If the file already exists, the file pointer will be placed at the end of the file (the new content will be written after the existing content). Otherwise, a file will be created for writing.
a+Open the file in read-write mode. If the file already exists, the file pointer will be placed at the end of the file (the new content will be written after the existing content). Otherwise, a file will be created for writing.
ab+Open the file in binary format and adopt append mode. The file pointer will be placed at the end of the file (the new content will be written after the existing content), otherwise, a file will be created for writing.
# print('d:\note1.txt')
#The problem of escape characters can be avoided in the following ways
# print('d:\\note1.txt')
# print(r'd:\note1.txt')
# print('d:/note1.txt')
# file1=open('d:/note1.txt')  #Specifies the path of the file to be read or written. When the second parameter is not written, it defaults to the read mode
# print(file1.read())  #Read the contents of the entire file and print it out
# file1.close()  #Close file

The operation results are as follows:

The bright moon in front of the bed is suspected to be frost on the ground.
Raising my head, I see the moon so bright; withdrawing my eyes, my nostalgia comes around.

Process finished with exit code 0
file2=open('d:/note2.txt','a')  #r read mode, w write mode, all previous contents will be cleared before writing, and a append write mode
file2.write('Carved fences and jade masonry should still be there,Just Zhu YangAi.')
file2.close()

The operation results are as follows:

#r mode can only be read, w mode and a mode can only be written. If you need to read and write at the same time, you can use r+,w+,a+
#r + if the path does not exist, an error will be reported. When r + is written, it is overwritten and not cleared
file2_1=open('d:/note2.txt','r+')
file2_1.write('When is the moon')
print(file2_1.read())  #The first five characters cannot be read because the cursor position is already in position 6
file2_1.close()

The operation results are as follows:

still exist,Just Zhu YangAi.

Process finished with exit code 0
#w + if the path does not exist, a file will be generated. When writing, write the new content after clearing the previous content
file3=open('d:/note3.txt','w+')
file3.write('But make Longcheng fly in')
file3.close()
#A + if the path does not exist, a file will be generated. When writing, if there is content before, additional writing will be performed
file3=open('d:/note3.txt','a+')
file3.write(',Don't teach Hu Ma to spend Yin Mountain')
file3.close()

The operation results are as follows:

2, Close file

file.close()
The close() method flushes the information that has not been written in the buffer, and then closes the file. In this way, the contents that have not been written to the file can be written to the file.

3, Open file with

with open(r'D:\note3.txt','r') as file:
    content = file.read()
print(content)

The operation results are as follows:

But make Longcheng fly in,Don't teach Hu Ma to spend Yin Mountain

Process finished with exit code 0

4, Write file

  1. file.write(str)
    Writes a string to a file and returns the length of the written character
  2. file.flush()
    Refresh the internal buffer of the file and directly write the data of the internal buffer to the file immediately, rather than passively waiting for the output buffer to be written.
  3. file.writelines(sequence)
    Write a sequence string list to the file. Multiple lines are written at one time. If line breaks are required, add the line breaks of each line.

For example, taking a.txt file as an example, you can easily copy the data in a.txt file to other files by using the writelines() function. The implementation code is as follows:

f = open(r"D:\a.txt",'r')
w = open(r'D:\b.txt','w+')
w.writelines(f.readlines())
w.close()
f.close()

After executing the code, a b.txt file will be generated. The contents of the file contained in the file are exactly the same as a.txt.
It should be noted that when using the writelines() function to write multiple lines of data to the file, line breaks will not be automatically added to each line. The reason why the data is displayed line by line in the b.txt file is that the readlines() function reads the line break at the end of the line when reading the data of each line.

5, Read file

  1. Read the specified character
    file.read([size])
    size is an optional parameter, used to specify the number of characters to read, including "\ n" characters; If omitted or negative, all are read.
f = open(r"D:\a.txt",'r')
string1 =f.read(20)
# w.close()
print ("The file name is: ", f.name)
print(f"Read string: {string1}")
f.close()

The operation results are as follows:

The file name is:  D:\a.txt
 Read string: Sing when drinking, life is geometric!
For example, the morning dew is much more bitter

Process finished with exit code 0
f = open(r"D:\a.txt",'r')
string =f.read() #Read all
# w.close()
print ("The file name is: ", f.name)
print(string)
f.close()

The operation results are as follows:

The file name is:  D:\a.txt
 Sing when drinking, life is geometric!
For example, the morning dew is much more bitter.
Be generous and unforgettable.
How to relieve worries? Only Du Kang.
Qingqingzijin, leisurely my heart.
But for your sake, I ponder so far.
Yo yo, deer crow, eat wild apples.
I have a guest who plays the drum, the harp and the Sheng.
As bright as the moon, when can I do it?
Sorrow comes from it and cannot be cut off.
Cross the paths and cross the paths in vain.
Qikuo talks about the past and remembers the old kindness.
The moon is bright and the stars are rare. Black magpies fly south.
Three turns around the tree, what branch can we rely on?
The mountains are never tired of being high and the sea is never tired of being deep.
Zhou Gong spits and feeds, and the world returns to its heart.

Process finished with exit code 0
  1. tell() method
    The file.tell() method returns the current location of the file, that is, the current location of the file pointer
f = open(r"D:\a.txt",'r')
print(f.tell())
string1 =f.readline()
# Get current file location
pos = f.tell()
print("current location:%d"%(pos))
print ("The file name is: ", f.name)
print(f"The data read is:{string1}")

The operation results are as follows:

0
 current location:22
 The file name is:  D:\a.txt
 The data read is:Sing when drinking, life is geometric!

Process finished with exit code 0
  1. seek() method
    When using the read(size) method, it is read from the beginning of the file by default. If you want to start reading from the specified location, you can use the seek() method of the file object to move the pointer of the file to the new text, and then use the read(size) method to read.
    The syntax of the seek() method is as follows:
    file.seek(offset,whence)
    offset: used to specify the number of characters to be moved. The specific position is related to where. Positive to the end and negative to the start.
    Where: used to specify where to start calculation. A value of 0 means to calculate from the beginning of the file, 1 means to calculate from the current position, and 2 means to calculate from the end of the file; The default is 0.
    When using the seek() method, the value of offset is calculated based on two characters for one Chinese character and one character for English and numbers.
f = open(r"D:\a.txt",'r')
f.seek(2) #Offset two characters to the right, and Chinese characters account for two characters
string1 =f.read(3)
print ("The file name is: ", f.name)
print(f"The data read is:{string1}")

The operation results are as follows:

The file name is:  D:\a.txt
 The data read is:Wine as a song

Process finished with exit code 0
f = open(r"D:\a.txt",'r')
string1 =f.readline()
# Get current file location
pos = f.tell()
print("current location:%d"%(pos))
print(f"The data read is:{string1}")
f.seek(0)#Move the file pointer to the beginning of the file
print("current location:%d"%(f.tell()))
string2 =f.read(4)
print(f"The data read is:{string2}")
f.close()

The operation results are as follows:

current location:22
 The data read is:Sing when drinking, life is geometric!

current location:0
 The data read is:sing while drinking

Process finished with exit code 0

Since a non-zero offset is used when seek() is used in the program, (when 1 or 2 is used for where), the opening method of the file must include b, otherwise an io.unsupported operation error will be reported.

f = open(r"D:\a.txt",'r')
string1 =f.readline()
# Get current file location
pos = f.tell()
print("current location:%d"%(pos))
print(f"The data read is:{string1}")
#f.seek(4,1) indicates the current position and moves 4 characters to the end of the file
f.seek(4,1)#An error will be reported. The open mode does not contain b  
print("current location:%d"%(f.tell()))
string2 =f.read(4)
print(f"The data read is:{string2}")
f.close()

Operation results:

Traceback (most recent call last):
  File "E:/PC/untitled/practice/test.py", line 152, in <module>
    f.seek(4,1)#An error will be reported. The open mode does not contain b  
io.UnsupportedOperation: can't do nonzero cur-relative seeks

Process finished with exit code 1
f = open(r"D:\a.txt",'rb')
string1 =f.readline()
# Get current file location
pos = f.tell()
print("current location:%d"%(pos))
print(f"The data read is:{string1}")
f.seek(-4,2)#Move the end of the file 4 characters forward
print("current location:%d"%(f.tell()))
string2 =f.read(4)
print(f"The data read is:{string2}")
f.close()

Operation results:

current location:22
 The data read is:b'\xb6\xd4\xbe\xc6\xb5\xb1\xb8\xe8\xa3\xac\xc8\xcb\xc9\xfa\xbc\xb8\xba\xce\xa3\xa1\r\n'
current location:346
 The data read is:b'\xd0\xc4\xa1\xa3'

Process finished with exit code 0
  1. Read one line
    If the file is too large, it is easy to run out of memory by reading all the contents to the memory at one time. All files are usually read line by line.
with open(r"D:\a.txt",'r') as f:
    while True:
        line = f.readline()
        if line:
            print(line)
        else:
            break

The operation results are as follows:

The bright moon in front of the bed is suspected to be frost on the ground.

Raising my head, I see the moon so bright; withdrawing my eyes, my nostalgia comes around.

Process finished with exit code 0
with open(r"D:\a.txt",'r') as f:
    number = 0
    while True:
        number+=1
        line = f.readline()
        if line =='':
            break
        print(number,line,end="\n")

The operation results are as follows:

1 The bright moon in front of the bed is suspected to be frost on the ground.

2 Raising my head, I see the moon so bright; withdrawing my eyes, my nostalgia comes around.

Process finished with exit code 0
  1. Read all
    file,readlines() returns a list of strings. Each element is a line of the file.
with open(r"D:\a.txt",'r') as f:
    content = f.readlines()
    print(content)

The operation results are as follows:

['The bright moon in front of the bed is suspected to be frost on the ground.\n', 'Raising my head, I see the moon so bright; withdrawing my eyes, my nostalgia comes around.']

Process finished with exit code 0

Traversal after reading:

with open(r"D:\a.txt",'r') as f:
    contents = f.readlines()
    for content in contents:
        print(content)
The bright moon in front of the bed is suspected to be frost on the ground.

Raising my head, I see the moon so bright; withdrawing my eyes, my nostalgia comes around.

Process finished with exit code 0

Posted by kellydigital on Fri, 15 Oct 2021 19:42:33 -0700