Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.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
Python 如何打印每个文件的名称和目录中的内容?_Python_File_Python 3.x - Fatal编程技术网

Python 如何打印每个文件的名称和目录中的内容?

Python 如何打印每个文件的名称和目录中的内容?,python,file,python-3.x,Python,File,Python 3.x,我在一个目录中有许多文本文件,我想打印每个文件名及其内容。问题是内容从上一个文件复制到下一个文件。这是我的密码: import os directory = os.listdir('/Users/user/My Documents/test/') os.chdir('/Users/user/My Documents/test/') for file in directory: open_file = open(file,'r') read_file = open_file.rea

我在一个目录中有许多文本文件,我想打印每个文件名及其内容。问题是内容从上一个文件复制到下一个文件。这是我的密码:

import os
directory = os.listdir('/Users/user/My Documents/test/')
os.chdir('/Users/user/My Documents/test/')
for file in directory:
    open_file = open(file,'r')
    read_file = open_file.read()
    print(open_file.name)
    print("***************")
    print(read_file)
以打印输出为例:

a.txt
 This is file1.
 ***********
b.txt
This is file1. This file 2
。。
有什么建议吗?。提前谢谢你,你没有关闭文件,你应该使用
(退出后关闭文件),类似这样

import os

directory = os.listdir('/Users/user/My Documents/test/')
os.chdir('/Users/user/My Documents/test/')

for file in directory:
    print(file)
    print("***************")    
    with open(file, 'r') as openfile:
        print(openfile.read())
    print('\n')

你没有关闭文件。。。