我正在尝试从文件位置列表中获取文件名。认为它涉及字符串切片。
我得出的结论是:
L = ['C:\\Design\dw\file4.doc',
'C:\\light\PDF\downloads\list.doc',
'C:\\Design\Dq\file4g.doc',
'C:\\Design\Dq\file4r.doc',
'C:\\Design\Dq\file4k.doc',
'C:\\Design\Dq\ole.doc',
'C:\\GE\easy\file\os_references(9).doc',
'C:\\mate\KLO\Market\BIZ\KP\who\Documents\REF.doc']
LL = []
for a in L:
b = a.split('\')
for c in b:
if c.endswith('.doc'):
c.replace('.doc', '')
LL.append(c)
print LL
问题1:输出仍然包含“ .doc”。为什么,如何删除它们?
问题2:获取文件名的更好方法是什么?
谢谢。
第一个问题的答案是字符串是不可变的,.replace()不会修改字符串,即:
blaize@bolt ~ $ python
>>> s = "foobar"
>>> s2 = s.replace("o", "x")
>>> print s
foobar
>>> print s2
fxxbar
我对第二个问题的回答如下:
# I use ntpath because I'm running on Linux.
# This way is more robust if you know you'll be dealing with Windows paths.
# An alternative is to import from os.path then linux filenames will work
# in Linux and Windows paths will work in Windows.
from ntpath import basename, splitext
# Use r"" strings as people rightly point out.
# "\n" does not do what you think it might.
# See here: https://docs.python.org/2.0/ref/strings.html.
docs = [r'C:\Design\dw\file4.doc',
r'C:\light\PDF\downloads\list.doc',
r'C:\Design\Dq\file4g.doc',
r'C:\Design\Dq\file4r.doc',
r'C:\Design\Dq\file4k.doc',
r'C:\Design\Dq\ole.doc',
r'C:\Design/Dq/test1.doc', # test a corner case
r'\\some_unc_machine\Design/Dq/test2.doc', # test a corner case
r'C:\GE\easy\file\os_references(9).doc',
r'C:\mate\KLO\Market\BIZ\KP\who\Documents\REF.doc']
# Please use meaningful variable names:
basenames = []
for doc_path in docs:
# Please don't reinvent the wheel.
# Use the builtin path handling functions.
# File naming has a lot of exceptions and weird cases
# (particularly on Windows).
file_name = basename(doc_path)
file_basename, extension = splitext(file_name)
if extension == ".doc":
basenames.append(file_basename)
print basenames
祝你好运。Python是一种出色的语言。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句