Chapter 5 File Operations

open a file

open(file path, access mode, encoding=encoding method): Only existing files can be opened, otherwise an error will be reported

Access mode:

  r : read only (default)

  w : write only (overwrite)

    ~ open an existing file, create a new file if it does not exist

    ~w mode will overwrite the contents of the previous file

  a : write only (append)

#Open the file in the current directory 
f = open( ' test.txt ' , ' w ' ,encoding= ' UTF-8 ' )
f.close()
#Open the file in the relative path 
f = open( ' file/test.txt ' , ' w ' ,encoding= ' UTF-8 ' )
f.close()
#Open the file in the absolute path 
f = open( ' d://test.txt ' , ' w ' ,encoding= ' UTF-8 ' )
f.close()

 

write file

write(data) : write a string to the file, create the file if it does not exist

# w mode: [write-only] w mode will overwrite the content in the previous file 
fw = open( ' file/test.txt ' , ' w ' ,encoding= ' UTF-8 ' )
fw.write( ' hello ' )
fw.close()
# a mode: [append] 
fa = open( ' test.txt ' , ' a ' ,encoding= ' UTF-8 ' )
fa.write( ' Hello everyone ' )
fa.close()

writelines(data) : Write a sequence of strings (list, tuple) to the file, create the file if it does not exist

f = open('file/test.txt','w',encoding='UTF-8')
f.writelines([ ' Zhang San\n ' , ' Li Si\n ' , ' Wang Wu\n ' ])
f.close()

read file

read() : read all

fr = open('file/test.txt','r',encoding='UTF-8')
readall = fr.read()
print(readall)

readlines() : read all line by line and return each line as a list

fr = open( ' file/test.txt ' , ' r ' ,encoding= ' UTF-8 ' )
 #Read all line by line and return each line to a list 
readlines = fr.readlines()
 print (readlines)

readline() : read a line, each read starts from the cursor read from the previous line to read the next line

fr = open( ' file/test.txt ' , ' r ' ,encoding= ' UTF-8 ' )
 #Read a line, each time the cursor read from the previous line starts to read the next line 
readline1 = fr.readline ()
readline2 = fr.readline()
print('readline1={},readline2={}'.format(readline1,readline2))

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325291891&siteId=291194637