重复写入现有文件的值

时间:2014-03-03 03:03:34

标签: python c

我有一个看起来像这样的文件:

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

我想在文件中添加一个具有相同值(1或0)的列,以便文件如下所示:

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

我不确定该如何去做; C或Python中的任何东西都可以。

2 个答案:

答案 0 :(得分:1)

此脚本可以满足您的需求。

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()

对此的详细解释是location(以及其他可能的解决方案)

要点:

  

换行符位于该行的末尾,因此-d即将到来   一开始。为了解决这个问题,我们使用string.strip()来实现   从字符串的开头和结尾删除某些字符:

上面的脚本产生了这个:

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

答案 1 :(得分:0)

open with clause,读取列表行,在列表中每个元素的末尾添加" 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
相关问题