import csv
import re
import tempfile
import sys
import os
if sys.version_info >= (3, 3):
from os import replace
elif sys.platform == "win32":
from osreplace import replace
else:
from os import rename as replace
newHeaderList = []
with tempfile.NamedTemporaryFile(dir='.', delete=False) as tmp, \
open('myFile.txt', 'rb') as f:
r = csv.reader(f, delimiter = '\t')
w = csv.writer(tmp, delimiter = '\t', quoting=csv.QUOTE_NONNUMERIC)
header = next(r)
for h in header:
headerNoSpace = re.sub("\s+", "_", h.strip())
newHeaderList.append(headerNoSpace)
w.writerow(newHeaderList)
for row in r:
w.writerow(row)
os.rename(tmp.name, new_text_filepath)
new_txt = csv.reader(open('newFile.txt', "rb"), delimiter = '\t')
out_csv = csv.writer(open('myFile.csv', 'wb'))
out_csv.writerows(new_txt)
4条答案
按热度按时间bwleehnv1#
尝试使用列表理解。
z9gpfhce2#
尝试使用重命名?
h43kikqp3#
我抛弃了Pandas,只使用了Python 2.7中的CSV模块。
hujrc8aj4#
你可以使用regex作为
sep
来删除头中的所有空格:这里
\s
表示一个空白字符,*
表示匹配前面的表达式(这里是\s
)零次或任意次。我猜你正在阅读一个像这样的文件
或者像这样
两者都可以使用上面的代码。但是,在
sep
中使用正则表达式可能会减慢阅读过程,因为'c'引擎不支持正则表达式,因此将使用'python'引擎。阅读非常大的文件时要小心。