Python open file, file read / write operation, with mode, file common function example analysis

Time:2021-7-24

This article gives examples of Python opening files, file reading and writing operations, with mode, and common file functions. Share with you for your reference, as follows:

Open file:

In Python 3, the function to open a file is:

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)

Parameter Description:

File -- file name
Mode - open mode, default read-only mode
Buffering -- if the value of buffering is set to 0, there will be no deposit. If the buffering value is 1, the line will be registered when accessing the file. If the buffering value is set to an integer greater than 1, it indicates that this is the buffer size of the register. If a negative value is taken, the buffer size of the deposit area is the system default.
Encoding - encoding method of the open file

Mode introduction:

r: Read only mode (default)

w: Write only mode. If the file does not exist, it will be created. If it does exist, the written data will overwrite the original data

b: Binary mode

t: Text mode

+: writable and readable mode

a: Append mode. If the file exists, the file pointer points to the end of the file (append data). If it does not exist, it is created

R +: read append mode, read first and then append

W +: write read mode, write first, which means that the original content is lost and read again.  

  • If the file contains non ascll characters, encoding must be used, otherwise an exception will be thrown:

image

print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.read())
f.close()
-----------------
Operation results:
my
sas
aaa
fsafsa
chinese
chinese
Gourd baby

The file must be closed after use: file pointer. Close()


File operation:

Read operation:

The contents of the read file are as follows:

image

  • Reads() reads everything
print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.read())
f.close()
---------------------------
Operation results:
my
sas
aaa
fsafsa
chinese
chinese
Gourd baby
  • Readline() reads a line
print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.readline())
f.close()

-----------
Operation results:
my
  • Readlines () is to read out all the contents and organize them into a list
print("r".center(50,'-'))
f=open("file.txt",encoding="utf-8")
print(f.readlines())
f.close()




#------------------------r-------------------------
#Operation results:
['my \ n', 'SAS \ n', 'AAA \ n', 'fsafsa \ n', 'Chinese \ n', 'Chinese \ n', 'huluwa \ n', '\ n']
  • The R + mode determines the position of the pointer according to the read content

print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")
# print(f.readline())
f.write("hello mike")
f.close()

result:

image

 


print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")
print(f.readline())
f.write("hello mike")
f.close()

New results:

image 

Write operation:

  • Write(): writes a string to a file
myfile=open("myfile1","wb")
myfile.write(b"nnnnnn")
My-write ("myut. F"))
myfile.close()
  • Writelines writes an iteratable object to a file

myfile=open("myfile1","wb")
myfile.write(b"nnnnnn")

myfile.writelines([b'1',b'2',b'3',b'4'])
myfile.close()
  • When you need to read it immediately after writing, use w +, and then set the file pointer back to the file header:

myfile=open("myfile1","wb+")
myfile.write(b"nnnnnn")
myfile.seek(0)
print(myfile.read())
myfile.close()
      • If you need to read a specific position, you can use variables to record the position
myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
site=myfile.tell()
myfile.write(b"2nnnnnn")
Myfile.seek (site) ## read the next paragraph
print(myfile.read())
myfile.close()

with:

  • In order to close the file conveniently, python adds the with function. When the with body is executed, the open file will be closed automatically:
With open ("file. TXT", "R +", encoding = "UTF-8") as F: ## will automatically execute f.close()
 print(f.tell())
 f. Write ("King Kong")
 for line in f:
  print(line,end="")
  • You can open multiple files at the same time:

with open("file.txt",'r') as f ,\
open("file.new",'r') as m:
 print(f.read(),m.read())

File common functions:

File. Close(): close the file. After closing, the file can no longer be read or written

File. Seek (offset [, where]): sets the current location of the file

File. Tell(): returns the current location of the file.

myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
site=myfile.tell()
myfile.write(b"2nnnnnn")
Myfile.seek (site) ## read the next paragraph
print(myfile.read())
myfile.close()

File. Flush(): flush the internal buffer of the file and write the data of the internal buffer to the file immediately, because the file is not immediately


import time
myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
time.sleep(10)
# myfile.flush()
myfile.write(b"2nnnnnn")
myfile.close()

The above code is not written to “1nn2nnnn” until the program is completed


import time
myfile=open("myfile1","wb+")
myfile.write(b"1nnnnnn")
myfile.flush()
time.sleep(10)
myfile.write(b"2nnnnnn")
myfile.close()

From the above code, you can see that “1nnn” has been written before the program sleep

File. Truncate ([size]): intercept the file from the beginning of the file to the specified location, and the original file will be overwritten.

Document content:

image

print("r".center(50,'-'))
f=open("file.txt","r+",encoding="utf-8")

print(f.readline())
print("----truncate()-------")
print(f.tell())
m=f.tell()
f. Truncate (m) # content is truncated from position 0 to the specified position, regardless of the current cursor position
f.close()

After execution, file content:

image

For more information about python, readers who are interested can see the topics on this site: summary of Python file and directory operation skills, summary of Python text file operation skills, tutorial on Python data structure and algorithm, summary of Python function use skills, summary of Python string operation skills, and classic tutorial on getting started and advanced python

I hope this article is helpful to python programming.

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]