2019-10-23

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')

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 键盘录入一个文件夹路径,统计该文件夹(包含子文件夹)中,每种类型的文件及个数, 注意:用文件类型(后缀名,不包含....
    5c9721263eb5阅读 1,594评论 0 0
  • * 把一个目录中的所有内容copy到另一个目录 public static void main(String[]...
    5c9721263eb5阅读 775评论 0 0
  • 从键盘接收一个文件夹路径,统计该文件夹大小 public class Demo1 { static long le...
    5c9721263eb5阅读 1,256评论 0 0
  • 序 ---写给和我一样不爱背单词的小朋友们 在我上学的时候,我也很懒,懒得学习,懒得背单词,那时候总感觉各种各样的...
    若有所得必有所失阅读 1,864评论 0 0
  • 不曾想过女儿会喜欢上水,进而喜欢上了游泳,最终还把被世人誉为水上芭蕾的体育项目——花样游泳,作为自己专属的兴趣爱好...
    渔夫镕谷阅读 3,505评论 2 12

友情链接更多精彩内容