python知识积累(四)——文件操作

来源:互联网 发布:linux的shell 编辑:程序博客网 时间:2024/06/10 03:40
按行读取文件里的内容:

try:f = file('test.txt','r')except:print "cannot find 'test.txt' "sys.exit(1)else:while True:line = f.readline()if len(line) == 0:breakrec = str(line).strip()

(file函数有三个选项。

r是read

w是write  。f.write(teststring)

a是append)

注:最后加上strip()函数,可以把string类型值的行首和行尾/t /n等去掉。否则可能会加上line的换行符。最后还最好f.close()一下结束缓冲流。


遍历指定文件夹下的文件:

path = "./"filelist = os.listdir(path)filelist.sort()for x in range(0,len(filelist)):filename = filelist[x]print filename
注:import os


拷贝文件0到另一个文件1(文件名为绝对路径)

shutil.copy(pathname0,pathname1)

删除文件(文件名为绝对路径)

os.remove(pathname)

 


If you have any questions or ideas ,please feel free to contact me : )

thx.^^


QQ: 1623213673


原创粉丝点击