简体   繁体   English

如何将文本从文件复制到 Python 中的列表?

[英]How to copy text from a file to a list in Python?

I have a couple of files inside a folder that I am trying to pull out text from, reason being that I eventually want to add this text into a newly created separate file.我试图从中提取文本的文件夹中有几个文件,原因是我最终想将此文本添加到新创建的单独文件中。 My tactic is to initialize a list and populate it with the text from each file, one by one.我的策略是初始化一个列表并用每个文件中的文本一个一个地填充它。 I have called this list myLines .我将此列表称为myLines

myLines = []

 for line in f:
        myLines.append(line)
    for element in myLines:
        f.write(myLines)

I get an error, and I know that it has something to do with .write() not accepting myLines because its a list rather than an argument.我得到一个错误,我知道它与.write()不接受myLines ,因为它是一个列表而不是一个参数。 How would I go about turning the content of mylines into an acceptable argument for the write() method?我 go 如何将mylines的内容转换为write()方法可接受的参数?

Thanks谢谢

IDK what's your intention of using myLines as the variable name. IDK 您使用myLines作为变量名的意图是什么。 Given what you described it should be a list of texts, not a list of lines.根据您的描述,它应该是文本列表,而不是行列表。

my_texts = []

# populate my_texts
for filename in input_files:
    with open(filename) as f:
        my_texts.append(f.read())

# write new file
with open('new_file_path.txt', 'w') as f:
    f.write('\n'.join(my_texts))

assuming you want a new line separating texts from each file.假设您想要一个新行将文本与每个文件分开。

A more straightforward method would be to 1) open the output file in append mode ( open('out_file_path', 'a') ), and 2) read each input file in a loop, writing the content to the output file.更直接的方法是 1) 在 append 模式 ( open('out_file_path', 'a') ) 中打开 output 文件,以及 2) 循环读取每个输入文件,将内容写入 output 文件。

Try this -试试这个 -

    myLines = []

     for line in f:
            myLines.append(line)
        for element in myLines:
            f.write(str(myLines))

Just convert myLines to string.只需将 myLines 转换为字符串即可。 You can use classes also if you want to preserve the type- list, but, that will be a bit lengthy.如果你想保留类型列表,你也可以使用类,但是,这会有点冗长。

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

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