open one txt file from 100 to 1800 from /content/stack_overflow_16k/test/python in python

To open a range of text files from 100 to 1800 in Python, you can use a loop to iterate over the desired file names and open them one by one. Here's an example:

main.py
file_path = "/content/stack_overflow_16k/test/python"
start = 100
end = 1800

for i in range(start, end+1):
    file_name = f"{file_path}/file{i}.txt"
    with open(file_name, "r") as file:
        content = file.read()
        # Do something with the file content here
        print(content)  # For example, printing the content

331 chars
12 lines

In this example, we're assuming that the file names follow a pattern like "file100.txt", "file101.txt", and so on. Adjust the file name pattern according to your specific filenames.

First, we define the file path where the files are located (file_path). Then, we define the start and end numbers of the file range (start and end).

Next, we use a loop (for i in range(start, end+1)) to iterate from the start to the end number (including the end number).

Within the loop, we generate the file name using f-string formatting and open each file using with open(file_name, "r") as file. The "r" mode is used to open the file for reading.

Finally, we can do something with the file content, like printing it. You can replace print(content) with any code specific to your use case.

related categories

gistlibby LogSnag