python operation file - 2

fw.flush() #Force the data in the buffer to be written to the disk
Example:
fw = open('username','w')
fw.write('hhh')
fw.flush()
(solve the problem: write a file may not be written to the file when


#replace file content

1. Simple and rude (disadvantages: when the file is relatively large, it occupies too much memory and runs slowly)

1. Open a file and get all its content (disk -> memory)
2. Modify the content
3. Clear the content of the original file
4. Write the new content to the file

f = open('username','a+')
f.seek(0)
all_str = f.read()
new_str = all_str.replace('123456','78910')
f.seek(0)
f.truncate() #清空文件内容
f.write(new_str)
f.close()


Example: Add a string 'str_' to each line
f = open('username','a+')
f.seek(0)
all_str = ''
for i in f:
all_str = all_str + 'str_'+ i
f. seek(0)
f.truncate() #Empty file content
f.write(all_str)
f.close()

 

2. Open two files

1. Open two files
2. A file
3. Write a line to b file
4. a.txt a.txt.bak
5. Delete the a file, change the b file name to the a file name, and replace it

Example: Modify the file and change all a in the file words to b

import os
with open('words', encoding = 'utf-8') as f,open('word','w',encoding = 'utf-8') as ff:
for line in f:
n_line = line. replace('a','b') #replace 'a' with 'b'
ff.write(n_line)
os.remove('words') #delete file
os.rename('word','words') # Modify the file name, replacing 'words' with 'word'

 

The difference between #.writelines() and write():

f.write() #Only write strings
f.writelines() #It will help us to write the loop once (only once), and can automatically loop the list for writing
(such as: f.writelines(['12345','4534 '])


Note: The difference between for line
in f: and for line in f.readlines()
for line in f: ---- read line by line; high efficiency
for line in f.readlines() ------- - one-time read

Guess you like

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