[英]Python, string slicing (getting file names from a list of file locations)
我正在嘗試從文件位置列表中獲取文件名。 認為它涉及字符串切片。
我得出的結論是:
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是一種出色的語言。
[file.split('\\')[-1].split('.')[0] for file in L]
實際上,您沒有在示例中進行任何切片。 您正在拆分和替換。 因為我們知道文件名和擴展名將始終是路徑的最后一部分,所以我們可以在分割后使用負索引來訪問它。
一旦我們在句點上再次分割,文件名將始終是第0個元素,因此我們只需抓住它並將其添加到列表中即可。
編輯:我只是注意到此方法將包含\\f
路徑有問題,因為這是一個特殊的Python字符。
如果文件名中沒有空格或其他符號,請嘗試此操作
[re.findall('\w+.doc$', L) for x in L]
嘗試看看
ntpath模塊
首先,replace方法返回具有替換值的字符串。 它不會更改字符串。 所以你需要做
c = c.replace('.doc', '')
第一個答案:replace返回字符串的副本,因此您不保存更改。
第二個答案:因為諸如'\\f'
類'\\f'
組合被解釋為utf-8字符,所以您需要獲取幾個路徑的原始表示。
因此,棘手的部分是將字符串格式化為其原始表示形式。 為此,我使用了這個答案的raw()
一旦有了此功能,我們就可以很好地操作字符串。
我用過re.split
來接受unix和dos格式的路徑
>>> L = [re.split(r'[\/\\]', raw(path)) for path in L]
>>> 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']]
現在L
包含路徑部分的列表,因此您可以訪問文件名及其擴展名,獲取每個列表的最后一個元素
>>> L_names = [path_parts[-1] for path_parts in L if path_parts[-1].endswith('.doc')]
>>> L_names
['file4.doc', 'list.doc', 'file4g.doc', 'file4r.doc', 'file4k.doc', 'ole.doc', 'os_references(9).doc', 'REF.doc']
首先要注意的是,您應該使用原始字符串( r
前綴)輸入列表:
L = [r'C:\\Design\dw\file4.doc',
r'C:\\light\PDF\downloads\list.doc',
…]
否則,將在文件名中插入字符(通常將\\…
替換為單個字符)。
Python 2有一個專門用於處理路徑的子模塊,它為您提供了預期的結果:
from os.path import basename, splitext
print [splitext(basename(path))[0] for path in L]
請注意,路徑和此腳本必須在使用相同路徑分隔符( /
或\\
)約定的系統上運行(通常應該是這種情況,因為路徑通常在計算機上本地有意義)。 您可以改為執行以下操作,使其專門用於Windows路徑(在任何操作系統上):
from ntpath import basename, splitext
然后,您可以在任何計算機上使用:
['file4', 'list', 'file4g', 'file4r', 'file4k', 'ole', 'os_references(9)', 'REF']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.