raven
raven

Reputation: 17

Using Python, able to iterate files from another directory but unable to read contents

I need to iterate through all the .txt files inside another directory from current directory and read the contents.

Am able to iterate thw filenames, but when tried to read the contents, the output is blabk while there is data in the files.

Upvotes: 0

Views: 53

Answers (2)

user14944294
user14944294

Reputation: 1

for file in files :
 print(file)
 print("printing success file")
 k = open(extracted_files_path+file,"r")
 print(extracted_files_path + file)
 print("ending printing success file")
 print(k.read())
 print(type(file))

Output:

printing success file ending printing success file //below is blank, whereas the file contents are expected// <class 'str'>

The above is the code and the actual output I'm getting for the question - raven.

Upvotes: 0

Adham Elshabasy
Adham Elshabasy

Reputation: 63

To do that here is an example of how to iterate on every text file in the current directory

# Import the module OS
import os

# Choose Current Directory
directory = os.getcwd()

# Iterate over every file in the directory
for filename in os.listdir(directory):
    # get the full path by concatenating the file name with the directory
    path = directory + "\\" + filename
    # Check if this file is a text file
    if path.endswith(".txt"):
        # Open the text files in the path
        text_file = open(path, 'r')
        # Read and print the contents of these files (Including the Python Script)
        print(text_file.read())

You can change the current directory with any directory you need.

If you have a problem with other Directories try using double backslashes in the URL like this

directory = 'C:\\Users\\USER\\Desktop\\Text Files'

Upvotes: 1

Related Questions