1.文件读写示例:读写、文件指针移动
words = 'Winter is coming!' #写入的数据 with open(r'.. estfilescompanies.txt','a+') as f: f.writelines(' ') f.writelines(words) f.seek(0,0) #移动文件指针到文件开头 cNames = f.readlines() print(cNames)
2.批量文件处理示例:统计文件行数
ef countLines(fname): '统计文件里内容的行数' try: with open('..\testfiles\' + fname) as f: data = f.readlines() except FileNotFoundError: print(fname + 'does not exist') lens = len(data) print(fname + ' has ' + str(lens) +' lines') files = ['data1.txt','data2.txt','data3.txt'] for fname in files: countLines(fname)
改进:统计某文件夹下的各TXT文件行数
import os def countLines(fname): '统计文件里内容的行数' try: with open(fname) as f: data = f.readlines() except FileNotFoundError: print(fname + 'does not exist') lens = len(data) print(fname.split('\')[1] + ' has ' + str(lens) +' lines') path = '../testfiles' for fname in os.listdir(path): if fname.endswith('.txt'): file_path = os.path.join(path,fname) countLines(file_path)
3.创建保存输出文件的目录
import os if os.path.exists('./output'): shutil.rmtree('./output') #如果存在非空的该目录,则删除该目录 os.mkdir('./output') #创建所需的目录
dir()
help()