[英]How to take full windows file path as user input and work with the file
我正在嘗試用 python 編寫一個程序,它將采用 Windows 文件路徑(使用反斜杠而不是正斜杠)並將文件轉換為另一種文件類型。 我認為input()
和使用反斜杠的窗口的某種組合是導致錯誤的原因。
例如,用戶會輸入類似
C:\用戶\用戶\下載\文件.tdms
我想告訴用戶從他們的文件資源管理器中復制文件路徑並將其粘貼到程序中。 我無法更改用戶輸入的內容,它必須采用上述形式。
到目前為止,這是我的代碼:
from nptdms import TdmsFile
from pathlib import Path, PurePosixPath
path = Path(input('enter file path: '))
path1 = PurePosixPath(path)
print(path1)
with open(path1, mode='r') as f:
tdms_file = TdmsFile.read(f)
tdms_file.to_csv(path + '.csv')
這是我得到的錯誤:
(base) H:\Private\ahirani\python TDMS to CSV>testing.py
enter file path: "C:/Users/user/Downloads/file.tdms"
"C:/Users/user/Downloads/file.tdms"
Traceback (most recent call last):
File "H:\Private\ahirani\python TDMS to CSV\testing.py", line 11, in <module>
with open(path, mode='r') as f:
OSError: [Errno 22] Invalid argument: '"C:/Users/user/Downloads/file.tdms"'
看起來您正在使用PurePosixPath
盡管您的問題是專門針對 Windows 的。 我會嘗試在官方文檔中列出的Path
對象上使用WindowsPath
和特定的打開方法。 此外,看起來您的輸入周圍有一組額外的雙引號
from nptdms import TdmsFile
from pathlib import WindowsPath
input_path = input('enter file path: ')
path = WindowsPath(input_path.replace('"', ''))
with path.open() as f:
tdms_file = TdmsFile.read(f)
tdms_file.to_csv(path + '.csv')
我無法立即訪問 Windows 機器來測試它,但它應該可以工作。 測試您的問題的好方法是搜索您的錯誤並嘗試將其硬編碼為調試步驟。 即看看這個SO 線程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.