简体   繁体   English

Python:尝试将字符串写入新文件时,仅写入字符串的最后一行

[英]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. 我尝试使用“ a”代替“ w”来写入新的文件,如在不同的堆栈溢出线程中指定的那样。

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)

What you are doing is only writing the last field1 value to the output file. 您正在执行的操作只是将最后一个field1值写入输出文件。 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)

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM