Reputation: 1039
I need to read the contents of a file from the list of files from a directory with os.listdir
. My working scriptlet is as follows:
import os
path = "/Users/Desktop/test/"
for filename in os.listdir(path):
with open(filename, 'rU') as f:
t = f.read()
t = t.split()
print(t)
print(t)
gives me all the contents from all the files at once present in the directory (path
).
But I like to print the contents on first file, then contents of the second and so on, until all the files are read from in dir.
Please guide ! Thanks.
Upvotes: 0
Views: 4863
Reputation: 46859
os.listdir
returns the name of the files only. you need to os.path.join
that name with the path the files live in - otherwise python will look for them in your current working directory (os.getcwd()
) and if that happens not to be the same as path
python will not find the files:
import os
path = "/Users/Desktop/test/"
for filename in os.listdir(path):
print(filename)
file_path = os.path.join(path, filename)
print(file_path)
..
if you have pathlib
at your disposal you can also:
from pathlib import Path
path = "/Users/Desktop/test/"
p = Path(path)
for file in p.iterdir():
if not file.is_file():
continue
print(file)
print(file.read_text())
Upvotes: 1
Reputation: 9745
First, you should find the path of each file using os.path.join(path, filename)
. Otherwise you'll loop wrong files if you change the variable path
. Second, your script already provides the contents of all files starting with the first one. I added a few lines to the script to print the file path and an empty line to see where the contents end and begin:
import os
path = "/Users/Desktop/test/"
for filename in os.listdir(path):
filepath = os.path.join(path, filename)
with open(filepath, 'rU') as f:
content = f.read()
print(filepath)
print(content)
print()
Upvotes: 1
Reputation: 774
You can print the file name. Print the content after the file name.
import os
path = "/home/vpraveen/uni_tmp/temp"
for filename in os.listdir(path):
with open(filename, 'rU') as f:
t = f.read()
print filename + " Content : "
print(t)
Upvotes: 1