python 3.x - How to read multiple lines in a txt file in a loop? -


i have directory containing several txt.files. interested in first 7 characters of each line. created dictionary takes keys name of files , values first 7 character of each row in each file. then, made 2 loops below:

files = glob.glob('/users/andreasportelli/desktop/sqldata/*')  customer = {"customer_id":[],"order_id":[]}  #create dictionary  file in files:      x = open(file, 'r', encoding='ascii', errors='replace')      customer["customer_id"].append(str(file))                      file in files:      x = open(file, 'r', encoding='ascii', errors='replace')      customer["order_id"].append(x.readline(7)) 

the problem in way reads first line , not lines. how make iterate on each line in each file?

thanks

you need loop file names once, , nested loop grab each line in file. hope helps!

files = glob.glob('/users/andreasportelli/desktop/sqldata/*')  customer = {"customer_id":[],"order_id":[]}  #create dictionary  file in files:     customer["customer_id"].append(file)                        line in open(file, 'r', encoding='ascii', errors='replace'):         customer["order_id"].append(line[:7])      

Comments