文件操作
sheet.txt文件内容
Tom,8 Jack,7 Tyke,3
读取文件
def file_op(): with open('sheet.txt', 'r') as f: lines = f.readlines() for line in lines: name, age = line.rstrip().split(',') print('{} is {} years old'.format(name, age))
open()第一个参数是文件名,第二个参数是模式。文件的模式一般有四种,读取(r),写入(w),追加(a)和读写(r+)。如果希望按照二进制数据读取,则将文件模式和b一起使用(wb, r+b…)
要读取文件内容,并把年龄和名字的顺序交换存成新文件age_name.txt,这时可以同时打开两个文件:
with open('name_age.txt', 'r') as fread, open('age_name.txt', 'w') as fwrite: line = fread.readline() while line: name, age = line.rstrip().split(',') fwrite.write('{},{}\n'.format(age, name)) line = fread.readline()
把对象进行序列化,那么可以考虑用pickle
def serialize(): lines = ["I'm like a dog chasing cars.", "I wouldn't know what to do if I caught one...", "I'd just do things."] with open('lines.pkl', 'wb') as f: pickle.dump(lines, f) with open('lines.pkl', 'rb') as f: lines_back = pickle.load(f) print(lines_back)
异常处理
在深度学习中,尤其是数据准备阶段,常常遇到IO操作。这时候遇到异常的可能性很高,采用异常处理可以保证数据处理的过程不被中断,并对有异常的情况进行记录或其他动作:
for filepath in filelist: # filelist中是文件路径的列表 try: with open(filepath, 'r') as f: # 执行数据处理的相关工作 ... print('{} is processed!'.format(filepath)) except IOError: print('{} with IOError!'.format(filepath)) # 异常的相应处理 ...
立志如山 静心求实
浙公网安备 33010602011771号