1、文件内容读取
a.txt
teestttttttttttttt
teestttttttttttttt
teestttttttttttttt
teestttttttttttttt
teestttttttttttttt
readFile.py
# 格式 file = open(文件路径,操作模式); file.read(); # file.readline(); #按行读取 file.close(); # example def readText(filePath,mode): file = open(filePath,mode); # 打开文件并制定文件操作模式 #file.seek(6); # 跳过多少字符进行读取 while True: line = file.readline(); # 分行全部读取 if line == '' or line is None: # 去除空行 break; print line; ''' print file.read(); # 全部读取 ''' file.close(); #调用文件读取函数 readText(R"E:\a.txt","r");# 文件路径具体制定
2、文件内容写入
# 用法 file=open(文件路径,操作权限); file.write(内容); file.close(); # example def writeText(filePath,mode): file=open(filePath,mode); i=0; while i<5: file.writelines("teestttttttttttttt\n"); i=i+1; file.close(); # 调用函数执行文件创建 writeText(r"E:\a.txt","w");
3、显示指定路径下的文件列表
# os模块 os.listdir("指定路径"); # example #!/usr/bin/python2.7 # __*__ encoding:UTF-8 __*__ import os; fileDir=os.listdir("./"); for i in fileDir: print i;
4、便利指定路径下的文件目录
#!/usr/bin/python2.7 #__*__ coding: UTF-8 __*__ import os; class FileTest: def __init__(self): pass; def __getFileAndDir__(self,filePath): tmp=os.walk(filePath,topdown=True); for root,dirs,files in tmp: # 遍历输出目录 for i in dirs: print os.path.join(root,i); # 遍历输出文件 for i in files: print os.path.join(root,i); a=FileTest(); a.__getFileAndDir__("F:\\test");
运行结果:
5、待定