[英]How to replace a column in a text file using a list?
我想根據另一個文本文件中的值替換文本文件中的列。 我跳過了前3個標題行,並將文件1的第二列讀入列表L,並希望替換文件2中的列2。 以下是我所擁有的:
L = []
for index, line in enumerate(open("C:/file1.txt", "r")):
if index <= 2:
continue
else:
L.append(line.split()[1])
例如:
L = ['2.3','1.2']
和文本文件是:
x y z
1.1 2.1 1.4
1.9 1.8 2.1
我想用列表L值替換變量y下的值。 任何建議將是感激的。
假設列表中的元素數與文件中的行數相同,這是一種實現方法。 還假設您要在元素之間使用制表符。 還要假設“第2列”表示第二列,其python索引為1。 在OSX或Linux上,可以通過在命令后放置> editedfile.txt
來捕獲編輯的文件。 如果有四列或更多列,則只需放置elements[2:]
而不是elements[2]
:
# This must have the same number of values as lines in the file
L = ['2.3','1.2']
with open("file1.txt", "r") as f:
# skip the first line but output it?
print f.readline().rstrip('\n')
for value,line in zip(L,f):
elements = line.split()
print "{}\t{}\t{}".format(elements[0],value,elements[2])
輸出(中間值已更改為2.3
和1.2
,我替換了帶有空格的制表符進行格式化):
x y z
1.1 2.3 1.4
1.9 1.2 2.1
您可能需要itertools.izip
或itertools.izip_longest
:
import itertools
with open(fname1) as f1, open(fname2) as f2:
for line1, line2 in itertools.izip(f1, f2):
pass # some computations here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.