我目前正在嘗試撰寫一個簡單的 python 腳本,該腳本使用我在文本檔案中寫下的檔案路徑打開一個檔案夾或檔案夾串列。
import os
with open('filepaths.txt') as f:
[os.startfile(line) for line in f.readlines()]
我的問題是,每當我運行此代碼時,python 都會將這些行讀取為其非原始形式。反斜杠加倍,每個字串中都有一個新行“\n”。
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'D:\\Nitro\\Downloads\n'
我試圖在變數上使用 repr() 來解決這個問題。它沒有洗掉反斜杠,而是進一步加倍。
import os
with open('filepaths.txt') as f:
[os.startfile(repr(line)) for line in f.readlines()]
FileNotFoundError: [WinError 2] The system cannot find the file specified: "'D:\\\\Nitro\\\\Downloads\\n'"
我還嘗試使用字串替換功能將“\”替換為“”。那沒起效。
uj5u.com熱心網友回復:
該readlines方法正確讀取檔案,并保留每行中的尾隨換行符。您只需要在將字串用作路徑名之前從字串中洗掉換行符,這通常使用以下str.rstrip方法完成:
for line in f: # no need to use the readlines method for iteration
os.startfile(line.rstrip())
您在問題中包含的錯誤訊息中的路徑名包含雙反斜杠,因為它與repr函式一起顯示,反斜杠已經轉義,而不是因為路徑名讀取不正確。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526195.html
標籤:Python细绳视窗小路
上一篇:填充字串陣列時檢查重復項
