简体   繁体   English

使用python查找文件名

[英]Find the file name using python

I have a file with the following format in filename.txt file.我在 filename.txt 文件中有一个具有以下格式的文件。

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.我能够很好地阅读它,但无法存储在 Pandas 数据框或列表或字典中。

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.存储在任何数据框或字典中的目的是与 excel 文件结果进行比较。

Using split() :使用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:详细说明给出的答案,应用于字符串的split()方法通过\\\\将其拆分,考虑以下示例:

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: [-1]索引获取其中的最后一个元素,因此:

print(s.split('\\')[-1]) 

Would give:会给:

hhhhhhhhhh8db

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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