我正在尝试在.txt文件中的大量数据之间添加“,”,我也想删除第二行。
这是我的txt文件的示例
1 1 139 178 128 83 140 140 87 87
2 1 199 204 130 111 198 198 89 89
3 1 188 182 107 120 183 183 109 109
......
'....'这里意味着数千个数据。
我希望在新的.txt文件中打印结果
这是我想要的结果。
1, 139, 178, 128, 83, 140, 140, 87, 87
2, 199, 204, 130, 111, 198, 198, 89, 89
3, 188, 182, 107, 120, 183, 183, 109, 109
.....
我真的希望这里有人可以帮我解决这个问题,非常感谢你的帮助!
谢谢!
答案 0 :(得分:0)
首先,遍历各行:
with open(filename) as f:
for line in f:
# can process the line here
现在让我们看看我们可以对每一行做些什么:
words = line.split() # split on whitespace
del words[1] # remove the word at index 1
joined = ", ".join(words)
print(joined) # can print to stdout, or write to another file
后续更新:
在此示例中打开文件f
后,您可以将其视为行的迭代器。这就是for line in f
有效的原因。您也可以像处理任何其他迭代器一样操纵它,但是您想要做的是有一些副作用,这就是原因:
如果你的内存中有一个列表,并且只想访问某些项目,那么尽管涉及效率低下,但很容易将其分割并迭代它:
lines = [...] # a list of lines in memory
# inefficient - creates expensive intermediate lists, one for each slice, and another one for the concatenated list
for line in lines[2:12] + lines[15:22]:
# process line
# slightly more efficient - creates less intermediate lists, one for each slice
from itertools import chain
for line in chain(lines[2:12, lines[15:22]):
# process line
如果你使用islice
要注意它甚至更贵 - islice
可以使用整个列表直到到达切片,而不是有效切片。
f
f
确实是行的迭代器,但它只是向前发展。这很棒 - 您可以使用这样的数十亿行来处理文件,而不是使用太多的内存 - 但这也意味着一旦islice
消耗了它就行了。您需要找到一种方法来过滤所需的行而无需“随机访问”,即无需在序列中向前和向后跳过任意数量的步骤。如果将行索引添加到迭代中,则可以执行此操作。
这是一个微不足道的方式:
def line_index_is_interesting(index):
return 2 <= index <= 11 or 15 <= index <= 21
with open(filename) as f:
index = 0
for line in f:
if line_index_is_interesting(index):
# process line
index += 1
这样你只需处理一行,从不使用大量内存。通过添加'index'变量的状态,您可以轻松做出决定。
是的,它是一个名为enumerate的内置函数:
with open(filename) as f:
for i, line in enumerate(f):
if line_index_is_interesting(i):
# process line