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:
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'))
f.writelines(['333\n','444\n'])
f.writelines([bytes('333\n',encoding='utf-8'),'444\n'.encode('utf-8')])
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)
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:
lines = f_read.readlines()
for n,line in enumerate(tqdm.tqdm(lines)):
if n == 50000:
pass
current_user = int(line.split(' ')[0])
current_time = int(line.split(' ')[1])
current_load = float(line.split(' ')[2].strip())*1000
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)
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)
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
|