2

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.

1
  • Look for split() Commented Apr 20, 2019 at 17:48

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

i am not sure with -1 usage. Please share more thought.
@user3256224 the split() function basically splits the string by \\ and create a list of it. [-1] grabs the last element in the list, i.e. hhhhhhhhhh8db
@user3256224 added an edit with the explanation as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.