Home > database >  How to move through files in python
How to move through files in python

Time:11-13

Does anyone know how to move through one file to the other if they are in the same directory?

Example: in file "A.txt" is written the name of the next file, meaning "B.txt," then in "B.txt", is written the name of the next file - "C.txt," and the content of "C.txt" is "A.txt," forming the chain "A.txt"-"B.txt"-"C.txt". BUT, there might be any N amount of files, not only 3.

I tried looping through the files, although I couldn't do anything with it.I have never worked with chaining files and their contests so i am completely lost,even one small advice would be appreciated.

CodePudding user response:

You can loop and at each iteration, read the content of the current file and then try to open a file using that content.

Check this example:

file = "a.txt"

while True:
    try:
        print(f"Opening file {file}")

        with open(file) as f:
            file = f.read()
    except IOError:
        print(f"Error opening file {file}")

This will loop forever while it can open a file using the contents of the previous file.

Now, depending on what's your objective, you can do that in other ways that don't use infinite loops, for example.

CodePudding user response:

A simple approach to your problem could be this one:

starting_file = "A.txt"
f = open(starting_file,"r")
next_file = "unknown"
while next_file != starting_file: # the loop condition will change regarding what you want to achieve
    next_file = f.read()
    f.close()
    f = open(next_file,"r")
    print(next_file)

you read the name of the following file and you then open it.

  • Related