简体   繁体   English

连接 python 中的文件

[英]concatenating files in python

I have files in a directory and i want to concatenate these files vertically to make a single file.我在一个目录中有文件,我想垂直连接这些文件以制作一个文件。

input

file1.txt   file2.txt
1              8
2              8
3              9

i need output我需要 output

1
2
3
8
8
9

My script is我的脚本是

import glob
import numpy as np
for files in glob.glob(*.txt):
    print(files)
    np.concatenate([files])

but it doesnot concatenate vertically instead it produces last file of for loop.Can anybody help.Thanks.但它不会垂直连接,而是生成 for 循环的最后一个文件。有人可以帮忙吗。谢谢。

There's a few things wrong with your code, Numpy appears a bit overkill for such a mundane task in my opinion.您的代码有一些问题,我认为 Numpy 对于这样一项平凡的任务来说似乎有点矫枉过正 You can use a much simpler approach, like for instance:您可以使用更简单的方法,例如:

import glob

result = ""
for file_name in glob.glob("*.txt"):
    
    with open(file_name, "r") as f:
        
        for line in f.readlines():
            result += line
print(result)

In order to save the result in a .txt-file , you could do something like:为了将结果保存.txt-file中,您可以执行以下操作:

with open("result.txt", "w") as f:
    f.write(result)

This should work.这应该工作。

import glob

for files in glob.glob('*.txt'):
    fileopen = open(r"" + files, "r+")
    file_contents = fileopen.read()
    output = open("output.txt", "a")
    output.write(file_contents)
    output.close()

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

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