文章目录
python文件操作
1.文本文件的打开模式
import os
文件句柄 = open('文件路径+文件名', '模式')
例子
f = open("test.txt","r",encoding = “utf-8”)
f = open(file = "d:/python/test.txt","r",encoding = “utf-8”)
“r” ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
“w”, 只写模式【不可读;不存在则创建;存在则清空内容】
"a",只追加写模式【不可读;不存在则创建;存在则只追加内容】
"+" 表示可以同时读写某个文件
"r+",读写【可读,可写】
"w+",写读【可读,可写】
"a+",写读【可读,可写】
2.read()、readline() 、readlines()
with open(path, 'r', encoding='utf-8') as f_read: #python读文件
lines = f_read.readlines() #读取每一行数据,存放于列表中
lines = f_read.read() #读取整个文件
lines = f_read.readline() #读取一行内容,光标移动到第二行首部以字符串的形式返回结果
3.write()、writelines( )
write()要写入字符串
writelines()既可以传入字符串又可以传入一个字符序列,并将该字符序列写入文件。 注意必须传入的是字符序列,不能是数字序列。
f.write('1111\n222\n') #针对文本模式的写,需要自己写换行符
f.write('1111\n222\n'.encode('utf-8')) #针对b模式的写,需要自己写换行符
f.writelines(['333\n','444\n']) #文件模式
f.writelines([bytes('333\n',encoding='utf-8'),'444\n'.encode('utf-8')]) #b模式
4. f.close() f.closed()
f.close() #关闭文件
f.closed()#查看文件是否关闭
5.with open as f打开方法
这种打开文件的方式不用写f.closed关闭文件
with open('/path/to/file', 'r') as f:
with open("test.txt","r",encoding = “utf-8”) as f:
6.f.encoding
取文件打开的编码
f = open("test11.py","w",encoding="gbk")
f.write("222\n")
f.close()
print(f.encoding)
输出
gbk
示例:
def read_origin_data(self, origin_data_path=ORIGIN_DATA_PATH, flag=None):
all_data_paths = os.listdir(origin_data_path) #os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
for each_path in all_data_paths:
path = origin_data_path + '/' + each_path+'/' + each_path
all_user_loads = {}
with open(path, 'r', encoding='utf-8') as f_read: #python读文件
lines = f_read.readlines() #读取每一行数据,以列表得形式存储
for n,line in enumerate(tqdm.tqdm(lines)): #Tqdm 是一个快速,可扩展的Python进度条
if n == 50000:
pass
current_user = int(line.split(' ')[0]) # split() 通过指定分隔符对字符串进行切片 输出分割的第一个
current_time = int(line.split(' ')[1]) #输出分割的第二个
current_load = float(line.split(' ')[2].strip())*1000
# strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
# 该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
time_load = [current_time, current_load]
if current_user not in all_user_loads.keys():
all_user_loads[current_user] = [time_load]
else:
all_user_loads[current_user].append(time_load)
# break
f_read.close() #关闭文件
# 给用户数据排序
all_user_nums = all_user_loads.keys()
for user in all_user_nums:
current_user_data = all_user_loads[user]
current_user_data = np.array(current_user_data) #array创建数组
sort_index = np.lexsort((current_user_data[:, 1], current_user_data[:, 0]))
sorted_user_data = current_user_data[sort_index, :]
all_user_loads[user] = sorted_user_data
if flag == 'day':
print("正在对数据预处理!")
days_user_loads = self.all_to_days(all_user_loads)
print("数据预处理完成!")
elif flag == 'month':
print("正在对数据预处理!")
days_user_loads = self.all_to_months(all_user_loads)
print("数据预处理完成!")
else:
days_user_loads = self.all_to_years(all_user_loads)
print("正在写入数据!")
self.write_data(days_user_loads, WRITE_DATA_PATH, flag)
print("写入数据完成!")
return