首页 > 解决方案 > 将多个文本文件合并为一个文本文件

问题描述

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

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 中还有一些其他的问题,强调如何去做。即使我也尝试过它们,但我无法正确实现它。

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

标签: arrayspython-3.xstringnumpyfile

解决方案


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

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)

推荐阅读