I have a bunch of.txt files in a folder. The text files look like
0 45 67 78 56
1 56 45 35 45
5 56 66 34 21
I want only the first character of each line (for instance here I want 0
, 1
, and 5
and store them in a list like [0,1,5]
). Now I want to store these lists along with the filename as a key-value pair in a dictionary named classes. classes should look like:
classes={'Q.txt'=[0,1,1,9],
'T.txt'=[0,1],
...}
Code:
path = "C:/....../" # path to the folder
l=[]#empty list to store
classes={} # my dictionary
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
for line in f.readlines():
l.append(int(line[0]))
classes[filename.split(os.sep)[1][:-4]]=l
Now what I'm getting is:
classses={'Q.txt': [0,0,1,1,9,0,1,............],
'T.txt': [0,0,1,1,9,0,1,............],
...}
meaning it is appending the entire list of all the characters in all the files when I just want dictionary to contain the list corresponding to the respective filename. How do I fix this?
So what you need to do is to reset l
at the start of the loop. You can use os.path.basename
to get the filename from the full path.
path = "C:/....../" # path to the folder
classes={} # my dictionary
for filename in glob.glob(os.path.join(path, '*.txt')):
l=[]#empty list to store
with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
for line in f:
l.append(int(line[0]))
classes[os.path.basename(filename)]=l
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.