0

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 directories? 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?

3
  • By the way, even though we were able to figure out your problem and solve it, I'm still confused by what you meant by "Is that typical of dictionaries?" I don't see any dictionaries anywhere in your question, and I don't know what the "that" refers to.
    – abarnert
    Commented Aug 22, 2013 at 21:32
  • @abarnert Oh wow, I'm sorry. It's been a long day, I definitely meant to say directories. And you answered the 'that' in your answer - my brain is just not working today. Thanks so much!
    – hjames
    Commented Aug 22, 2013 at 21:39
  • OK, I just wanted to make sure I didn't miss half your question or something.
    – abarnert
    Commented Aug 22, 2013 at 22:36

2 Answers 2

8

The problem is this line:

for file in sub_dir:

If you print(file) each time through the loop, it should be obvious what's wrong: subdir is a string, so you're just iterating over the characters of that string one by one.

What you probably wanted here is:

for file in os.listdir(sub_dir):

As the docs explain, listdir:

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

3

sub_dir isn't a directory; it's the name of a directory.

for file in sub_dir:

iterates over the characters in the name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.