【百度领航团】【零基础Python】文件操作学习
收藏
课程链接:https://aistudio.baidu.com/aistudio/course/introduce/7073
这几天的学习营收获颇丰,感谢AI Studio提供这样的机会。以后也会留在AI Studio继续研究学习。
常规文件操作:
从文件读取数据:
# 基础 f = open('work/train_data_cor.txt') line = f.readline() print(line) line = f.readline() print(line) f.close() # 进阶 f = open('work/train_data_cor.txt') for line in f: print(line) f.close()
读取数据遇到问题:
# 使用异常跳过有问题的数据 f = open('work/train_data_wrg.txt') for line in f: data = line.strip().split(',') try: print('姓名:'+data.pop(0)+'生日:'+data.pop(0)+'时间:'+str(data)) except: pass f.close() # 增加代码判断 f = open('work/train_data_wrg.txt') for line in f: data = line.strip().split(',') if len(data) != 1: print('姓名:'+data.pop(0)+'生日:'+data.pop(0)+'时间:'+str(data)) f.close()
写入数据到文件:
# 基础 f = open('work/data.txt','w') f.write('this is file content') f.close() # 读、写文件都可以用with方法简化 with open('work/train_data.txt') as f: ...
JSON是使用最广的数据传输格式,转化数据为JSON格式:
# 对象转JSON import json class Athlete(json.JSONEncoder): def __init__(self,a_name,a_dob=None,a_times=[]): self.name = a_name self.dob = a_dob self.times = a_times ... with open('work/train_data_cor.txt') as f: data = f.readline().strip().split(',') ath = Athlete(data.pop(0),data.pop(0),data) print(ath) ath_json = json.dumps(ath.__dict__) # 保存JSON with open('work/json.txt','w') as f: json.dump(ath_json,f) # 读取JSON with open('work/json.txt') as f: ath = json.load(f)
使用os模块进阶文件操作:
import os #返回当前工作目录 current_path = os.getcwd() print('当前路径:'+current_path) #改变当前工作目录 os.chdir('/home/aistudio/work') #运行mkdir命令 os.system('mkdir today') from pathlib import Path #返回当前绝对路径 abs_path = os.path.abspath('') print('abs_path:'+abs_path) #路径是否存在 Path(abs_path).exists() #是否为文件夹 os.path.isdir('/home/aistudio/work/today') #返回当前路径下文件和文件夹名 print('当前路径:'+os.getcwd()) listdir = os.listdir() print(listdir)
os模块在工作学习中被广泛使用,值得好好研究学习。
0
收藏
请登录后评论
收获满满
满满的收获