【发布时间】:2018-06-08 21:17:24
【问题描述】:
我正在使用一组约 1000 个包含 GPS 数据的大型 (700MB+) CSV。时间戳当前位于 UTC 时区,我想将它们更改为 PST。
我编写了一个 Python 脚本来解析文件,用正确的值更新两个时间戳字段,然后将它们写入文件。最初我想尽量减少磁盘写入的次数,所以在每一行我都将更新的行附加到一个字符串中。最后,我对文件进行了一次大写操作。这对小文件按预期工作,但对大文件挂起。
然后我更改了脚本以在处理每一行时写入文件。这有效,不会挂起。
为什么第一个解决方案不适用于大文件,有没有比一次写一行文件更好的方法?
构建一个大字符串:
def correct(d, s):
# given a directory and a filename, corrects for timezone
file = open(os.path.dirname(os.path.realpath(sys.argv[0])) + separator() + d + separator() + s)
contents = file.read().splitlines()
header = contents[0]
corrected_contents = header + '\n'
for line in contents[1:]:
values = line.split(',')
sample_date = correct_time(values[1])
system_date = correct_time(values[-1])
values[1] = sample_date
values[-1] = system_date
corrected_line = ','.join(map(str, values)) + '\n'
corrected_contents += corrected_line
corrected_file = os.path.dirname(os.path.realpath(sys.argv[0])) + separator() + d + separator() + "corrected_" + s
with open (corrected_file, 'w') as text_file:
text_file.write(corrected_contents)
return corrected_file
写下每一行:
def correct(d, s):
# given a directory and a filename, corrects for timezone
file = open(os.path.dirname(os.path.realpath(sys.argv[0])) + separator() + d + separator() + s)
contents = file.read().splitlines()
header = contents[0]
corrected_file = os.path.dirname(os.path.realpath(sys.argv[0])) + separator() + d + separator() + "corrected_" + s
with open (corrected_file, 'w') as text_file:
text_file.write(header + '\n')
for line in contents[1:]:
values = line.split(',')
sample_date = correct_time(values[1])
system_date = correct_time(values[-1])
values[1] = sample_date
values[-1] = system_date
corrected_line = ','.join(map(str, values)) + '\n'
text_file.write(corrected_line)
return corrected_file
【问题讨论】:
-
我会说即使是第二种方法也很糟糕。检查我们以获得更好的文件阅读jeffknupp.com/blog/2016/03/07/python-with-context-managers
-
我同意:没有理由将整个文件读入内存并将其分成几行,如果您要在任何情况下一次处理一行。
标签: python database python-3.x csv