Python: adding values to columns in a text file

时间:2016-08-23 15:34:32

标签: python text-files

I have a text file that looks like:

0.0  3  0.1273  
4.0  3  -0.0227  
8.0  3  0.1273      

I want to change this so that it prints out column1 and column2 and replaces the values in column3 to '1' for each row. So I want the output file to look like:

0.0  3  1
4.0  3  1
8.0  3  1

How can I do this in python? I have a code that just reads and writes the text file as it is- not sure how to edit it so that it changes the third column. Any help will be much appreciated!

fname="file.txt"

results = []
for line in open(fname,'r'):
    col1=line.split()[0]
    col2=line.split()[1]
    col3=line.split()[2]
    data = col1,col2, col3
#data.insert(col3, 1)            #attempt1-this didnt work
#data.replace(col3, 1)           #attempt2-this didnt work
    results.append(data)
    print(data)                  #this just prints the file as it is

with open ('new_file.txt', 'w') as datafile:
    for data in results:
        datafile.write ('{0}\n'.format(' '.join(data)))

1 个答案:

答案 0 :(得分:1)

回想一下,元组是不可变的。您无法更改该值。 因此,当您执行data = col1, col2, col3时,data的值无法更改。只需直接与data分配col1, col2, 1即可。