I have many text files in a directory and I want to print each file name and its content. The problem is the content is duplicated from the previous file to the next file. Here is my code:
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)
it's print out as an example:
a.txt
This is file1.
***********
b.txt
This is file1. This file 2
.. any suggestion?..Thanks in advance
You don't close the files, and you should be using a with
(which closes the file after you exit), something like this
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.