【发布时间】:2019-12-15 01:29:45
【问题描述】:
我有一个大型(160 万行以上).csv 文件,其中包含一些带有前导空格、制表符和尾随空格甚至可能是尾随制表符的数据。我需要读取数据,去除所有空白,然后将行吐出到一个新的 .csv 文件中,最好使用最有效的代码,并且只使用 python 3.7 中的内置模块
这是我目前正在工作的内容,除了它只会一遍又一遍地吐出标题并且似乎没有处理尾随标签(虽然在尾随标签上并不是什么大问题):
def new_stripper(self, input_filename: str, output_filename: str):
"""
new_stripper(self, filename: str):
:param self: no idea what this does
:param filename: name of file to be stripped, must have .csv at end of file
:return: for now, it doesn't return anything...
-still doesn't remove trailing tabs?? But it can remove trailing spaces
-removes leading tabs and spaces
-still needs to write to new .csv file
"""
import csv
csv.register_dialect('strip', skipinitialspace=True)
reader = csv.DictReader(open(input_filename), dialect='strip')
reader = (dict((k, v.strip()) for k, v in row.items() if v) for row in reader)
for row in reader:
with open(output_filename, 'w', newline='') as out_file:
writer = csv.writer(out_file, delimiter=',')
writer.writerow(row)
input_filename = 'testFile.csv'
output_filename = 'output_testFile.csv'
new_stripper(self='', input_filename=input_filename, output_filename=output_filename)
如上所述,代码只是在一行中一遍又一遍地打印标题。我玩弄了 def 的最后四行的排列和缩进,得到了一些不同的结果,但我得到的最接近的是让它每次在新行上一次又一次地打印标题行:
...
# headers and headers for days
with open(output_filename, 'w', newline='') as out_file:
writer = csv.writer(out_file, delimiter=',')
for row in reader:
writer.writerow(row)
EDIT1:这是不正确剥离的结果。其中一些具有未删除的前导空格,有些具有未删除的尾随空格。似乎最左边的列被正确地去除了前导空格,但没有去除尾随空格;与标题行相同。
更新:这是我正在寻找的解决方案:
def get_data(self, input_filename: str, output_filename: str):
import csv
with open(input_filename, 'r', newline='') as in_file, open(output_filename, 'w', newline='') as out_file:
r = csv.reader(in_file, delimiter=',')
w = csv.writer(out_file, delimiter=',')
for line in r:
trim = (field.strip() for field in line)
w.writerow(trim)
input_filename = 'testFile.csv'
output_filename = 'output_testFile.csv'
get_data(self='', input_filename=input_filename, output_filename=output_filename)
【问题讨论】:
-
一定要用python,还是可以用更快更高效的,比如
awk或者sed? -
我可以使用其他东西,但我正在尝试自动执行此操作,因为它必须每月一次又一次地完成,并且我需要在清理后对数据进行一些计算它
-
使用
sed查看我的解决方案更新答案。 -
问题是我在必须完成这项工作的计算机上没有管理员权限......这需要这样的访问权限吗?我没有使用 shell 的经验
标签: python csv read-write