pythonwindowsuser-inputoserror

How to take full windows file path as user input and work with the file


I am trying to write a program in python that will take a windows file path (uses backslashes not forward slashes) and converts the file to another file type. I think some combination of input() and windows using backslashes is what is causing errors.

For example, the user would input something like

C:\Users\user\Downloads\file.tdms

I want to tell the user to copy the file path from their file explorer and paste it into the program. I cannot alter what the user inputs, it has to be in the above form.

Here is my code thus far:

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')

Here is the error I get:

(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"'

Solution

  • It looks like you are using PurePosixPath although your question is specifically about Windows. I would try using WindowsPath and the specific open method on the Path object as listed in the official documentation. Additionally it looks like you have an extra set of double quotes around your input

    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')
    

    I don't have immediate access to a Windows Machine to test this but it should work. Also good way to test what your issues are would be to search for your error and try hardcoding it as a debugging step. i.e. take a look at this SO thread