【问题标题】:Concatenation of Text Files (.txt files) with list in python?文本文件(.txt文件)与python中列表的连接?
【发布时间】:2019-05-13 08:33:54
【问题描述】:

假设我有两个文本文件 1.txt 和 2.txt

1.txt的内容为:

['Hi', 'I', 'am']

2.txt的内容为:

['a', 'boy']

如何以高效的方式加入相同内容并将其写入新文件,例如3.txt,应该如下所示:

['Hi', 'I', 'am', 'a', 'boy']

我试过了:

import os

file_list = os.listdir("path")
with open('out.txt', 'a+') as outfile:
   for fname in file_list:
       with open(fname) as infile:
          outfile.write(infile.read())

【问题讨论】:

标签: python python-3.x list file


【解决方案1】:

你可以试试这样的:

inputText = []
for file in ['1.txt','2.txt']:
    with open(file,'r') as file:
        inputText.extend(file.readlines()+['\n'])
with open ('3.txt','w') as output:
    for line in inputText:
        output.write(line)

with open ('3.txt','w') as output:
    for file in ['1.txt','2.txt']:
        with open(file,'r') as file:
            for line in file:
                output.write(line)
            output.write('\n')

编辑您的评论:

import re
inputList = []
for file in ['1.txt','2.txt']:
    with open(file,'r') as infile:
        for line in infile:
            inputList.extend(re.sub('[^A-Za-z0-9,]+', '', line).split(","))
print(inputList)
with open('3.txt','w') as outfile:
    for line in inputList:
        outfile.write(line + '\n')

【讨论】:

  • 谢谢范!如何在单个列表中指定输出,例如 ['Hi', 'I', 'am', 'a', 'boy']。从您的建议中产生的输出会产生单独的列表,例如 ['Hi', 'I', 'am',] 和 ['a', 'boy']
  • 谢谢@Van。您编辑的答案会在一个列表中产生输出,例如:["['Hi', 'I', 'am']", "['a', 'boy']"]。我需要将输出显示在单个列表而不是列表列表中。所需的输出应该是这种格式:['Hi', 'I', 'am', 'a', 'boy'].
  • 在 python 2 和 3 上测试过。希望它现在能满足你的要求。第三个 codeshippet 中的“inputList”应该是你想要的列表。
  • 对不起。我根据您的建议使用codeshippet -3 作为["['Hi', 'I', 'am']", "['a', 'boy']"] 获得输出。但是,我希望输出为:['Hi', 'I', 'am', 'a', 'boy']。两者之间不应有任何中间列表。所有的字符串都应该合并到一个列表中。
  • 我的错,我以为你读的是多行文本,上面的文本是你在 python 中的列表。生病编辑我的代码。我使用了一些字符串编辑使其成为你想要的 python 列表,但通常更容易将其保存为 txt 文件中的纯文本,当你读入它时它会变成一个 python 列表。
【解决方案2】:

您可以使用json module 从文件中加载 json,因此您将拥有一个包含字符串的列表。
您只需使用 + 运算符连接列表并保存:

import json

final_result = []
for file in ["1.txt", "2.txt"]:
    with open(file, 'r') as fd:
        final_result += json.load(fd)

with open("3.txt", 'w') as fd:
    json.dump(final_result, fd)

【讨论】:

  • 感谢埃尔登!我试过你的建议。如何指定 CWD 路径!
  • 默认情况下,Python 使用您当前的工作目录。如果要使用特定路径,可以在file 变量之前添加路径:with open(path + file, 'r') as fd:。如果要使用脚本所在的文件夹,可以使用path = os.path.dirname(os.path.realpath(__file__))
猜你喜欢
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 2016-10-24
  • 2021-05-31
  • 2018-07-01
相关资源
最近更新 更多