[英]Add numbers from a list to an existing file using python
I have a text file with say 14 lines, and I would like to add list items from a list to the end of each of these lines, starting with the 5th line. 我有一个说14行的文本文件,我想将列表中的列表项添加到每行的末尾,从第5行开始。 Can anyone help me out please.
谁能帮帮我。 eg I have this text file called
test.txt
: 例如,我有一个名为
test.txt
文本文件:
a b
12
1
four
/users/path/apple
/users/path/banana
..
..
and I have the following list 我有以下列表
cycle=[21,22,23,.....] 周期= [21,22,23,.....]
My question is how can add these list items to the end of the lines such that I get this: 我的问题是如何将这些列表项添加到行的末尾,这样我就可以得到:
a b
12
1
four
/users/path/apple 21
/users/path/banana 22
..
..
I am not very good at python and this seems like a simple problem. 我不太擅长python,这似乎是一个简单的问题。 Any help would be appreciated.
任何帮助,将不胜感激。
Something like this: 像这样:
for line in file.readlines():
print line.rstrip(), cycle.pop(0)
cycle = [21, 22, 23]
i = 0
with open('myfile.txt', 'r') as fh:
with open('new_myfile.txt', 'w' as fh_new:
for line in fh:
addon = ''
if i < len(cycle):
addon = cycle[i]
fh_new.write(line.strip() + addon + '\n')
i += 1
In general, you cannot modify a file except to append things at the end of the file (after the last line). 通常,您不能修改文件,只能在文件末尾(最后一行之后)附加内容。
In your case, you want to: 您的情况是:
You can do it in several ways. 您可以通过多种方式进行操作。 Load -> Write back modified string would be the simplest:
加载->写回修改后的字符串将是最简单的:
with open("path/to/my/file/test.txt", 'rb') as f:
# Strip will remove the newlines, spaces, etc...
lines = [line.strip() for line in f.readlines()]
numbers = [21, 22, 23]
itr = iter(numbers)
with open("path/to/my/file/test.txt", 'wb') as f:
for line in lines:
if '/' in line:
f.write('%s %s\n' % (line, itr.next()))
else:
f.write('%s\n' % line)
The issue with this method is that if you do a mistake with your processing, you ruined the original file. 这种方法的问题在于,如果您在处理过程中出错,则会破坏原始文件。 Other methods would be to:
其他方法将是:
As always, the Python doc is a definitely good read to discover new features and patterns. 与往常一样, Python文档绝对是发现新功能和新模式的好书。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.