本篇文章给大家带来的内容是关于python文件操作的相关知识介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1、文件操作
1-1 遍历文件夹和文件
import osrootdir = /path/to/rootfor parent, dirnames, filenames in os.walk(rootdir): for dirname in dirnames: print(parent is: + parent) print(dirname is: + dirname) for filename in filenames: print(parent is: + parent) print(filename is: + filename) print(the full name of the file is: + os.path.join(parent, filename))
1-2 获取文件名和扩展名
import ospath = /root/to/filename.txtname, ext = os.path.splitext(path)print(name, ext)print(os.path.dirname(path))print(os.path.basename(path))
1-3 逐行读取文本文件内容
f = open(/path/to/file.txt)# the first methodline = f.readline()while line: print(line) line = f.readline()f.close()# the second methodfor line in open(/path/to/file.txt): print(line)# the third methodlines = f.readlines()for line in lines: print(line)
1-4 写文件
output = open(/path/to/file, w)# output = open(/path/to/file, w+)output.write(all_the_text)# output.writelines(list_of_text_strings)
1-5 判断文件是否存在
import osos.path.exists(/path/to/file)os.path.exists(/path/to/dir)# only check fileos.path.isfile(/path/to/file)
1-6 创建文件夹
import os# make multilayer directorysos.makedirs(/path/to/dir)# make single directoryos.makedir(/path/to/dir)
以上就是python文件操作的介绍(代码示例)的详细内容。