### **Python练手小片段**
**1.** 实际需求:两个文件(csv或txt),每行最多15个项目,‘;’号为分隔符。 为方便导入pandas处理,进行以下处理(选择进行一个个多个操作):
* 移除文本文件的首行
* 合并两个文本文件
* ‘;’号替换为‘,’号
* 格式化为每行15个项目,不足15个项目的行,添加‘000’以达到15个项目的目的。
**1.1** 移除文本文件的首行
~~~
def remove_1st_line(infile):
"""Remove the 1st line of a txt file."""
file_str = ''
with open(infile, 'r') as f:
next(f) # Skip header line
for line in f:
file_str += line
with open(infile, 'w') as f:
f.write(file_str)
~~~
使用with open方式打开文件,然后使用next()跳过首行。把文件剩余内容写入一个大字符串。再写入文件。 针对不大的文本文件比较有效。
---
**1.2** 合并两个文本文件
~~~
def merge(folder, output_f_name):
"""Merge 2 (or more) txt/csv file to 1."""
# Obtain file name list
merge_file_dir = os.getcwd() + f'\\{folder}\\'
filenames = os.listdir(merge_file_dir)
print(f'---合并以下文件: {filenames}')
name, ext = os.path.splitext(filenames[0])
# CSV file is gb2312 generate by scale, TXT is utf-8, for our file
if ext == '.csv':
code = 'gb2312'
else:
code = 'utf-8'
# Open a new file, put content of filenames list into it
with open(output_f_name, 'w', encoding=code) as f:
# Get the filepath for open it,
for filename in filenames:
filepath = merge_file_dir + filename
# For each file, write it line by line to output file
with open(filepath, 'r', encoding=code) as f1:
temp = f1.readlines()
f.writelines(temp)
return output_f_name
~~~
需要合并的文件放在当前工作目录下的文件夹内。返回文件名以供其他函数调用。此程序是根据实际文件编写,code是判断本人使用的文件。csv与txt分别是不同机器生成的文件。编码不同。
___
**1.2** 替换
~~~
def alter(file_name, old_str, new_str):
"""Replace a str with another within a txt file"""
with open(file_name, 'r', encoding='utf-8') as f:
file_date = f.readlines()
for i, value in enumerate(file_date):
file_date[i] = file_date[i].replace(old_str, new_str)
with open(file_name, 'w', encoding='utf-8') as f:
f.writelines(file_date)
if __name__ == '__main__':
alter('kkk.txt', ';', ',')
~~~
替换文本文件内指定字符串为新字符串。
for循环内使用enumerate的原因:如果直接使用列表值迭代,在for循环内对列表值的更新并不能直接生效,达到更改列表的目的。需要引入一个中间值列表。不值得。
---
**1.3** 生成15个项目的行(意思就是14个逗号)
~~~
def format15(file_name):
"""Format each line of a text file to 15 items for importing into pandas"""
with open(file_name, 'r', encoding='utf-8') as f:
lines = f.readlines()
for i, value in enumerate(lines):
lines[i] = lines[i].split(',')
lines[i][-1] = lines[i][-1].strip()
for j in range(15 - len(lines[i])):
lines[i].append('000')
lines[i] = ','.join(lines[i]) + '\n'
with open(file_name, 'w', encoding='utf-8') as f:
f.writelines(lines)
~~~
基于同样的原因使用enumerate对列表值进行原地修改。生成的文件导入padas试试。
pandas读取一行一行的文本时,如果一行项目是15,另一行项目小于15,就报错。这是写个小片段的原因。
---
2. 待
3. 定