需求:
工作中需要计算上市公司碳排放数据,需要利用分读for循环进行文本值提取,然后进行匹配和记录写入,最后需要分析汇总,用于后续的深度数据挖掘。
解决:
def read_txt(inputpath, outputpath): with open(outputpath, 'w', encoding='utf-8') as file: with open(inputpath, 'r', encoding='utf-8') as infile:
data2 = []
for line in infile:
data_line = line.strip("\n").split() # 去除首尾换行符,并按空格划分
print(data_line)
data2.append([int(i) for i in data_line])
print(data2)
# 输出:[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
data = data2
for i in range(len(data2)):
for j in range(len(data2[i])):
data[i][j] = str(data2[i][j])
print(data)
# 输出:[['1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10']]
# 写入方法
for line in data2:
# data = '' + '\t'.join(str(i) for i in line) + '\n' # 用\t隔开
data = '' + ' '.join(str(i) for i in line) + '\n' # 用空格隔开
file.write(data)
if name == "main": input_path = '1.txt' output_path = '2.txt' read_txt(input_path, output_path)
数据来源: 上市公司碳排放数据
标签:分读,循环,排放量,print,path,line,txt,data,data2 From: https://www.cnblogs.com/idatawork/p/17678877.html