I have a file with the following format in filename.txt file.
h:\abc\abc_Foldhr_1\hhhhhhhhhh8db
h:\abc\abc_Foldhr_1\hhhhhhhhhh8dc
h:\abc\abc_Foldhr_1\hhhhhhhhhh8dx
h:\abc\abc_Foldhr_1\hhhhhhhhhh8du
h:\abc\abc_Foldhr_1\hhhhhhhhhh8d4
h:\abc\abc_Foldhr_1\hhhhhhhhhh8d5
h:\abc\abc_Foldhr_1\hhhhhhhhhh8d6
h:\abc\abc_Foldhr_1\hhhhhhhhhh8d7
h:\abc\abc_Foldhr_1\hhhhhhhhhh8d8
I was able to read it well but unable to store in pandas data frame or the list or dictionary.
import pandas as pd
#data = pd.read_excel ('/home/home/Documents/pythontestfiles/HON-Lib.xlsx')
data = pd.read_table('/home/home/Documents/pythontestfiles/filename.txt', delim_whitespace=True, names=('A'))
df = pd.DataFrame(data, columns= ['A'])
print(df)
and would like to list out the filename only as
hhhhhhhhhh8db
.
.
.
hhhhhhhhhh8d6
hhhhhhhhhh8d7
hhhhhhhhhh8d8
the purpose of storing in any data frame or dictionary is to compare against the excel file result.
Using split()
:
res = []
with open('filename.txt', 'r') as file:
content = file.readlines()
for line in content:
# print(line.split('\\')[-1]) # to print each name
res.append(line.split('\\')[-1]) # append the name to the list
print(res)
EDIT :
Elaborating on the answer given, the split()
method being applied on the string splits it by the \\\\
, Consider the following example:
s = 'h:\abc\abc_Foldhr_1\hhhhhhhhhh8db'
print(s.split('\\'))
Which gives the output:
['h:\x07bc\x07bc_Foldhr_1', 'hhhhhhhhhh8db']
The [-1]
index grabs the last element in it, hence:
print(s.split('\\')[-1])
Would give:
hhhhhhhhhh8db
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.