当前位置:网站首页>2. File operation - write

2. File operation - write

2022-07-06 08:17:00 wwanxinghao

1、 Pattern mode=w

#  Pattern mode=w  Write data to file , If the file does not exist, create a new file , If the file exists , Then empty the file and write again 
f = open(' New files .txt',mode='w',encoding='utf-8')
f.write(' the weather is nice today ')

2、 Write the data in the list to the text

Be careful :1. normal open Outside the loop ,

2. The list is connected after being written to the file , It needs to be separated by carriage return

#  A list is written to the file 
l = ['python','java','go']
f = open(' New files .txt',mode='w',encoding='utf-8')
for i in l:
    f.write(i)
    f.write('\n')

3. Append write (append):a

l = ['python','java','go']
f = open(' New files .txt',mode='a',encoding='utf-8')
for i in l:
    f.write(i)

4. File opening and playing need to be closed :f.close(), Not closing , When the file is large, it will consume server resources , File operation occupied , You need to wait until the program finishes running before releasing resources

 

原网站

版权声明
本文为[wwanxinghao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131833015247.html