0

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)))
3
  • 2
    data = col1, col2, 1 ? Commented Aug 23, 2016 at 15:38
  • 1
    This isn't python, but here is an easy way to do it from the command line... awk '{ print $1, $2, "1"; }' filename Commented Aug 23, 2016 at 15:42
  • @CharlesAddis +1 the right tool for the right job! :) Commented Aug 23, 2016 at 16:14

1 Answer 1

1

Recall that tuple is immutable. You can't change the value. So when you do data = col1, col2, col3 then data's value cannot be changed. Just simply assign data directly with col1, col2, 1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.