Python的學習:
操作文件:
write(),writelines(),writeline()只能讀取字符串
寫單行文件
def make_story(line,fname='story.txt'):
?? f=open(fname,'a')
?? f.write(line)
? ? f.close()
make_story('我歌唱每一座高山,\n')
多行寫文件
f=open('hello.txt','w+')
context=['hhhhhhhh\n','zzzzzzz\n']
f.writelines(context)
f.close()
在文件開頭插入文件
def insert_title(title,fname='hello.txt'):
? ? f=open(fname,'r+')
? ? temp=f.read()
? ? context=title+'\n'+temp
? ? f.seek(0)
? ? f.write(context)
? ? f.close()
insert_title('sssss')
#給每句話編序號
f=open('hello.txt')
lines=f.readlines()
#temp=''
for i in range(1,len(lines)+1):
? ? #temp=temp+str(i)+'.'+' '+lines[i-1]
? ? lines[i-1]=str(i)+'.'+' '+lines[i-1]
f.close()
f2=open('hello1.txt','w+')
f2.writelines(lines) #write,等系列函數(shù)只能寫入字符
f2.close()
#文件的狀態(tài)
import os
print(os.stat(r'F:\學習\研究生\2019-2020秋\python\hello1.txt'))
#文件的刪除
import os
if os.path.exists('hello1.txt'):
? ? os.remove('hello1.txt')
#文件的復寫
f1=open('hello.txt','r')
f2=open('hello2.txt','w+')
f2.write(f1.read())
f1.close()
f2.close()
復制文件的其他方法 shutil
copyfile(src, dst)
move(src, dst)
參數(shù)src表示源文件的路徑,dst表示目標文件的路徑,均為字符串類型。
import shutil
shutil.copyfile('hello.txt','copyhello.txt')
將文件hello.txt,移動到當前目錄,重命名為renamehello.txt
shutil.move('hello.txt','renamehello.txt')
將文件hello1.txt,移動到目錄XX
shutil.move('hello1.txt','目錄XX')