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,等系列函数只能写入字符
f2.close()
#文件的状态
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)
参数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')