Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python3中连接多个文件_Python_Python 3.x_Codeigniter_Ubuntu - Fatal编程技术网

如何在python3中连接多个文件

如何在python3中连接多个文件,python,python-3.x,codeigniter,ubuntu,Python,Python 3.x,Codeigniter,Ubuntu,这是我的代码: filenames = ['DAY_1.txt', 'DAY_2.txt'] with open('house_a.txt', 'w') as House_A: for fname in filenames: with open(fname) as copyfile: for line in copyfile: House_A.write(line) 我的文件夹存储

这是我的代码:

filenames = ['DAY_1.txt', 'DAY_2.txt']
    with open('house_a.txt', 'w') as House_A:
        for fname in filenames:
             with open(fname) as copyfile:
                for line in copyfile:
                House_A.write(line)
我的文件夹存储在

下载/Aras/House A/(DAY_1.txt,DAY_2.txt…)

我想将所有
DAY_1.txt
DAY_30.txt
连接到一个文件
House_a.txt


有人能告诉我一个简单的方法吗?

来帮助您解决代码中可能出现的问题。您正在执行写入操作,因此每次遍历要从中获取数据的文件时,您都将在循环中重新写入整个文件。实际上,您要做的是使用
'a'
(append)指令

此外,您正在读取的文件上循环,这实际上是不必要的。您可以使用
read
readlines
方法在不使用循环的情况下读取整个内容

这里有一个例子来帮助说明

假设已经存在两个文件:
f1.txt
f2.txt

f1.txt的内容

1
2
3
4
“f2.txt”的内容:

5
6
7
8
9

“f3.txt”的内容:

1
2
3
4
5
6
7
8
9
试试这个

with open('House_a.txt', 'w') as out:
    for file_name in os.listdir('folder/where/files_stored'):
        with open(file_name) as file:
            out.write(file.read())

os.listdir
显示目录中的所有文件。

您能告诉我们当前代码存在什么问题吗?是的,请解释您自己的实现中当前不起作用的内容。错误是-------------------------------------------------------------------IsDirectoryError Traceback(最后一次调用)in()1文件名=['DAY_1.txt','DAY_2.txt']--->2,其中open('/home/dhrumil/Downloads/Aras/House_A','w')作为outfile:3表示文件名中的fname:4表示open(fname)作为infle:5表示infle中的行:IsADirectoryError:[Errno 21]是一个目录:'/home/dhrumil/Downloads/Aras/House_a'@dhrumil请编辑您的问题,并将该错误放入您的问题中,并将其正确格式化。该错误清楚地告诉您,
/home/dhrumil/Downloads/Aras/House_a
是一个目录,而不是一个文件。请确保您传递了正确的路径,并创建了正确的路径和文件e、
os.path.join
(您的目录,文件名)`我理解代码,但如果我的all.txt文件存储在以下目录中:/home/dhrumil/Downloads/Aras/House_A我如何访问这些all文本files@Dhrumil那么你需要更好地解释你的问题。你的代码中发生了什么?你收到了什么错误?你需要提供所有这些详细信息。更新你的问题以包括所有imp了解你所面临的重要细节。
with open('House_a.txt', 'w') as out:
    for file_name in os.listdir('folder/where/files_stored'):
        with open(file_name) as file:
            out.write(file.read())