Blue Moon
Blue Moon

Reputation: 4681

How to read multiple lines in a txt file in a loop?

I have a directory containing several txt.files. I am interested only in the first 7 characters of each line. I created a dictionary that takes as keys the name of the files and as values the first 7 character of each row in each file. Then, I made 2 for loops like below:

files = glob.glob('/Users/andreasportelli/Desktop/sqldata/*')

customer = {"customer_id":[],"order_id":[]}  #create a dictionary

for file in files:
     x = open(file, 'r', encoding='ascii', errors='replace')
     customer["customer_id"].append(str(file))                   


for file in files:
     x = open(file, 'r', encoding='ascii', errors='replace')
     customer["order_id"].append(x.readline(7))

The problem is that in this way it only reads the first line and not all lines. How do I make it iterate on each line in each file?

thanks

Upvotes: 0

Views: 1510

Answers (1)

fivetentaylor
fivetentaylor

Reputation: 1297

You only need to loop the file names once, and then a nested loop to grab each line in the file. Hope that helps!

files = glob.glob('/Users/andreasportelli/Desktop/sqldata/*')

customer = {"customer_id":[],"order_id":[]}  #create a dictionary

for file in files:
    customer["customer_id"].append(file)                   
    for line in open(file, 'r', encoding='ascii', errors='replace'):
        customer["order_id"].append(line[:7])     

Upvotes: 1

Related Questions