简体   繁体   中英

How to read all files that name store in text file

I am using python to read all find that path's of file store in text file such as (name_path.txt)

0_7\069A07.JPG;0
0_7\070A02.JPG;0
0_7\070A03.JPG;0
20_36\003A25.JPG;1
20_36\003A35.JPG;1
20_36\057A23.JPG;1
20_36\057A25.JPG;1

In which first element is path of file, and second element (seperated by ";") store label. Now I want to use python to get:

  1. File path such as 0_7\\069A07.JPG and its label such as 0. (see in first row)

Could you help me to implement it? Thanks you so much Update This is what I am doing

infile = "name_path.txt"
data = open(infile, "r").readlines()
# Create a dictionary list
for line in data:
    row = line.split(";");
    pathname=row[0]
    label=row[1]

You can use a dictionary to store your labels as the key and the paths in a list :

infile = "name_path.txt"
d={}
with open(infile, "r") as f:
  for line in f:
    path,label = line.split(";")
    d.setdefault(label,[]).append(path)

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM