我正在尝试拆分路径以获取文件名、字符串的最后部分,并且我正在处理一个我无法解决的问题:
我的字符串:te = 'C:\Users\Desktop\TEST\Excel_Reports\1837.xlsx'
我这样做了:
>>> te.split('\\')
['C:', 'Users', 'Desktop', 'TEST', 'Excel_Reports\x01837.xlsx']
>>> te.split('\\')[-1]
'Excel_Reports\x01837.xlsx'
我不知道 \0
或 \number
有什么问题....是否有任何特殊的 Python 字符??
这是我想要得到的:
['C:', 'Users', 'Desktop', 'TEST', 'Excel_Reports', '1837.xlsx']
但我无法准确理解这一点。
PD:不是像 file_name = te[-5:-1] 这样的有效解决方案,因为 excel 文件的名称随时可能不同,但始终是数字。
编辑: 显示我是如何得到 te
folder = QtGui.QFileDialog.getExistingDirectory(None, "Load excel")
for f in os.listdir(folder):
if f.endswith(".xlsx"):
te= os.path.join(str(folder),str(f))
#bla, bla, bla,......
编辑:
感谢所有的回答和评论,它们为我指明了正确的方向。
但是,我只是通过替换这一行解决了这个问题:
te= os.path.join(str(folder),str(f))
对于这个:
te = os.path.join(folder,f)
然后,这有效:
te.split('\\')[-1].split('.')[0]
给出不带扩展名xlsx
的文件名(编号)
最佳答案
假设您有一个正确的路径,那么:
import os
# Note that we're using the **r** prefix to make it a raw string - backslashes don't escape
path = r'C:\Users\Desktop\TEST\Excel_Reports\1837.xlsx'
print os.path.split(path)[1]
# 1837.xlsx
您还可以进一步拆分以获取文件名的基数,例如:
print os.path.splitext(os.path.split(path)[1])[0]
# 1837
关于python - 用反斜杠分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26605076/