我有一个基本上看起来像这样的文件:
atom
coordinateX coordinateY coordinateZ
atom
coordinateX coordinateY coordinateZ
...
我正在尝试添加原子序数(从0开始),这样我的文件就会看起来像这样:
atom0
coordinateX coordinateY coordinateZ
atom1
coordinateX coordinateY coordinateZ
...
这是我的代码和我的问题:
readFile = open("coordinates.txt", 'r')
writeFile = open("coordinatesFormatted.txt", 'w')
index = 1
counter = 0
for lineToRead in readFile:
lineToRead = lineToRead.lstrip()
if index % 2 == 0:
counter = counter + 1
lineToRead+=str(counter)
writeFile.write(lineToRead)
index = index+1
readFile.close()
writeFile.close()
f = open('coordinatesFormatted.txt','r')
temp = f.read()
f.close()
f = open('coordinatesFormatted.txt', 'w')
f.write("0")
f.write(temp)
f.close()
在我运行代码后,我得到的不是我想要的输出:
0atom
coordinateX coordinateY coordinateZ
1atom
coordinateX coordinateY coordinateZ
...
任何帮助都将不胜感激!
您有两个组合问题,这是一个有趣的组合:计数器上的奇数/偶数问题和使用lstrip
而不是strip
:strip
删除了移动行的换行符。
我重写了你的代码,删除了最后一个无用的部分,现在它按预期工作了。
readFile = open("coordinates.txt", 'r')
writeFile = open("coordinatesFormatted.txt", 'w')
index = 1
counter = -1
for lineToRead in readFile:
lineToRead = lineToRead.strip()
if index % 2:
counter += 1
lineToRead+=str(counter) # append counter to atom without linefeed
writeFile.write(lineToRead+"n") # write line, adding the linefeed again
index += 1
readFile.close()
writeFile.close()
在循环中运行两个计数器可能会非常混乱。你没有正确地剥离这些线条。
以下操作用于用itertools.count
对象替换index
和count
。使用write
方法将新行字符添加到行中:
from itertools import count
c = count() # set up a counter that starts from zero
with open('coordinates.txt') as f, open('coordinatesFormatted.txt', 'w') as fout:
for line in f:
line = line.strip()
if line == 'atom':
line += str(next(c)) # get the next item from the counter
fout.write(line + 'n')