【问题标题】:Combine multiple text files into only one text file将多个文本文件合并为一个文本文件
【发布时间】:2021-11-08 04:39:20
【问题描述】:

我想将多个文本文件合并为一个文本文件,并读取其中的所有内容。但是,这些代码只读取一个文本文件并保存从一个文本文件中获取的数据。代码;

path = "/home/Documents/Python/"
     
read_files = glob.glob(path+"*.txt")

with open("contents.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())

我也尝试了几乎相同的另一个代码。但是,它无法将字符串转换为浮点数,因为文本文件中的第一行包含 # 字符。

x = np.array([float(raw) for raw in f.readlines()])

我知道 stackoverflow 中还有一些其他问题,重点介绍了如何去做。即使我也尝试了它们,但我无法正确实现。

我将不胜感激任何帮助或建议。

【问题讨论】:

  • 由于您的问题也被标记为 numpy,您可以使用 numpy 的 loadtxt 将数据作为 Numpy 数组读取。 loadtxt 函数支持读取/跳过不同类型的列以及标题。然后,您可以连接所有数组,并使用numpy.savetxt 保存它。或者,您可以使用 Pandas 库,它对 Numpy 的一些数据函数和表示具有更好的接口。

标签: arrays python-3.x string numpy file


【解决方案1】:

如果有人想使用其他方法,这些代码对我有用。我已经按照另一条路径为我自己的问题找到了解决方案。

all_files = glob.glob(path + "/*.txt")
all = []
for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    all.append(df)
frame = pd.concat(all, axis=0, ignore_index=True)

【讨论】:

    【解决方案2】:

    也许是这样的。

    import os
    import glob
    import pandas as pd
    os.chdir("C:\\")
    
    
    extension = 'csv'
    all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
    
    
    #combine all files in the list
    combined_csv = pd.concat([pd.read_csv(f) for f in all_filenames ])
    #export to csv
    combined_csv.to_csv( "C:\\combined_csv.csv", index=False, encoding='utf-8-sig')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-09
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      相关资源
      最近更新 更多