使用 python 查找文件名
Find the file name using python
我在 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
我能够很好地阅读它,但无法将其存储在 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)
并且只想将文件名列为
hhhhhhhhhh8db
.
.
.
hhhhhhhhhh8d6
hhhhhhhhhh8d7
hhhhhhhhhh8d8
存储在任何数据框或字典中的目的是与 excel 文件结果进行比较。
使用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)
编辑:
详细说明给定的答案,应用于字符串的 split()
方法将其拆分为 \
,请考虑以下示例:
s = 'h:\abc\abc_Foldhr_1\hhhhhhhhhh8db'
print(s.split('\'))
给出输出:
['h:\x07bc\x07bc_Foldhr_1', 'hhhhhhhhhh8db']
[-1]
索引获取其中的最后一个元素,因此:
print(s.split('\')[-1])
会给:
hhhhhhhhhh8db
我在 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
我能够很好地阅读它,但无法将其存储在 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)
并且只想将文件名列为
hhhhhhhhhh8db
.
.
.
hhhhhhhhhh8d6
hhhhhhhhhh8d7
hhhhhhhhhh8d8
存储在任何数据框或字典中的目的是与 excel 文件结果进行比较。
使用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)
编辑:
详细说明给定的答案,应用于字符串的 split()
方法将其拆分为 \
,请考虑以下示例:
s = 'h:\abc\abc_Foldhr_1\hhhhhhhhhh8db'
print(s.split('\'))
给出输出:
['h:\x07bc\x07bc_Foldhr_1', 'hhhhhhhhhh8db']
[-1]
索引获取其中的最后一个元素,因此:
print(s.split('\')[-1])
会给:
hhhhhhhhhh8db