Python 重复将值写入现有文件

Python 重复将值写入现有文件,python,c,Python,C,我有一个类似以下内容的文件: 76.049515 38.887974 20.341053 16.956047 72.749557 20.119661 28.935022 4.174813 ... ... 76.049515 38.887974 1 20.341053 16.956047 1 72.749557 20.119661 1 28.935022 4.174813 1 我想向文件中添加一个具有相同值(1或0)的列,以便文件如下所示: 76.049515 38.887974

我有一个类似以下内容的文件:

76.049515 38.887974
20.341053 16.956047
72.749557 20.119661
28.935022 4.174813
...       ...
76.049515 38.887974 1
20.341053 16.956047 1
72.749557 20.119661 1 
28.935022 4.174813 1
我想向文件中添加一个具有相同值(1或0)的列,以便文件如下所示:

76.049515 38.887974
20.341053 16.956047
72.749557 20.119661
28.935022 4.174813
...       ...
76.049515 38.887974 1
20.341053 16.956047 1
72.749557 20.119661 1 
28.935022 4.174813 1

我不知道该怎么办;C或Python中的任何东西都可以工作

此脚本将执行您正在寻找的操作

infile = open("inpu.txt", 'r') # open file for reading
outfile = open("output.txt","a") # open file for appending

line = infile.readline()    # Invokes readline() method on file
while line:
  outfile.write(line.strip("\n")+" 1\n")
  line = infile.readline()

infile.close()
outfile.close()
这是一个很好的详细解释(以及其他可能的解决方案)

总结:

换行符在该行的末尾,因此-d在后面 开始。为了解决这个问题,我们使用string.strip(),它允许 要从字符串的开头和结尾删除某些字符,请执行以下操作:

上面的脚本生成以下内容:

76.049515 38.887974 1
20.341053 16.956047 1
72.749557 20.119661 1
28.935022 4.174813 1
使用,读取列表中的行,在列表中每个元素的末尾添加
“1”
,最后写回:

with open('a.x', 'r+') as f:
    newlines=[line.strip()+' 1\n' for line in f] #strip off '\n's and then add ' 1\n'
    f.seek(0) #move to the start of file to overwrite it.
    f.writelines(newlines) #write the lines back.
#file closed automatically out of the with clause scope

你能创建一个新文件,然后替换旧文件吗?那就容易了,当然。那也可以。@user3288886那么你已经知道怎么做了?我现在正在尝试。到目前为止,没有。非常感谢!寻找答案和链接。这很有帮助。@user3288886如果这个答案确实解决了你的问题,你应该接受它。