If you have many files that you need to read and process, you can use a loop to iterate over the filenames and read each file's contents one at a time.
Here's an example:
import osdirectory = '/path/to/files/'for filename in os.listdir(directory): if filename.endswith(".txt"): file_path = os.path.join(directory, filename) with open(file_path, 'r') as f: file_contents = f.read() # process file contents |
In this example, we use the os module to list the files in the directory specified by directory. We then loop over each filename and check if it ends with .txt using the endswith() method.
If the file has the .txt extension, we construct the full file path using the os.path.join() method and open the file using a with statement. We then read the file's contents using the read() method and store them in the file_contents variable.
We can then process the file contents as needed. You can replace the comment # process file contents with your own processing code.
Note that this approach reads each file's contents into memory, so it may not be suitable for very large files. If you have large files to process, you can use a generator expression or a library like Dask to read and process the files in smaller chunks.