Kumaraguru Ramasamy
Kumaraguru Ramasamy

Reputation: 32

Python: Writing only the last line of the string when trying to write the string to a new file

I am reading a text file as a list and extracting only the first column of data with " " (keyboard space) as a split separator.

I am trying to write the resultant string data into a new file.

While I create and write the string data into the new file, only the last line of the string data is present in the newly created file.

For example, when I print the string data, I am able to see the entire string.

graphics/1.jpg
graphics/2.jpg
graphics/3.jpg
graphics/4.jpg
graphics/5.jpg

However, the new file is created but contains only the last line:

graphics/5.jpg

I tried using "a" instead of "w" for writing the new file as specified in a different stack overflow thread.

Not sure what is that I need to do to write the entire string data into the newly created file. Please help!

with open(fig_file, "r") as f:
        for line in f:
            fields = line.split(" ")
            field1 = fields[0]
            print(field1)

with open("list.txt","w") as wp:
        wp.write(field1)

Upvotes: 0

Views: 971

Answers (2)

frederick99
frederick99

Reputation: 1053

You are only writing one line to the file, ever!

This should work.

lines = []
with open(fig_file, "r") as f:
        for line in f:
            fields = line.split(" ")
            field1 = fields[0]
            print(field1)

            lines.append(field1)


with open("list.txt","w") as wp:
        wp.writelines(lines)

Upvotes: 2

DSC
DSC

Reputation: 1153

What you are doing is only writing the last field1 value to the output file. If you want to write all fields, you need to write them during the loop like this:

with open(fig_file, "r") as f:
    with open("list.txt","w") as wp:
        for line in f:
            fields = line.split(" ")
            field1 = fields[0]
            wp.write(field1)

Upvotes: 1

Related Questions