Open files in directory in for loop Python
I'm a beginner programmer.
In my Py script, I need to create a CSV file with information from
multiple files within a sub directory. When I ran my code, I got the
error: FileNotFoundError: [Errno 2] No such file or directory: '1'. I
printed the contents of the directory and found that the directory doesn't
read the file's actual name but replaces it with a number or character.
Question: Is that typical of dictionaries? Because in research, it seemed
like other people are able to use
for file in directory:
open(file, "r")
correctly. Am I missing something?
My code:
sub_dir = datetime + "-dir"
os.mkdir(sub_dir)
with open("csv.txt", "a") as csv, open("data.txt") as data:
csv.write("Title" + "\r")
for x in data:
csv.write("," + x)
csv.write("\r" + "Data")
for file in sub_dir:
csv.write(file)
csv.write(", " + "Word1")
csv.write(", " + "Word2")
csv.write(", " + "Word3")
csv.write(", " + "Word4")
csv.write("\r")
f = open(file, "r")
lines = f.readlines()
for line in lines:
line.replace("word5=", ", ")
line.replace("word6=", ", ")
line.replace("word7=", ", ")
csv.write(line)
Question: How can I change my code so that file is the actual file name?
No comments:
Post a Comment