-2

The requirement of code is I have to take the file path from the user in the console and perform some action on that file. Users can give paths in windows style or mac style. for the mac or Linux, the path code is working fine but for the windows path its give an error (because of ) how to handle this error as I can't use the 'r' string in that as it's coming from the user.

user_path = input('give text file path: ') 
file = open(user_path, 'r') 
words = file.read().split() 
print('total number of words: ', len(words))

And if I provide path: C:\desktop\file.txt its give error

  • 1
    Please give some examples. – SAL Jul 08 '21 at 11:11
  • 2
    Please post your code. – Ram Jul 08 '21 at 11:22
  • user_path = input('give text file path: ') file = open(user_path, 'r') words = file.read().split() print('total number of words: ', len(words)) And if I provide path: C:\desktop\file.txt – Ashok Khoja Jul 08 '21 at 11:39
  • convert it to absolute path using `os.path.abspath(user_path)` then check if it exists using `os.path.exists(user_path)` if True then open the file else it will throw the exception in case of file not exists. – Abhishek Jul 08 '21 at 13:30
  • import os path = input("path: ") path_abs = os.path.abspath(path) print(path_abs) file = open(path_abs, 'r') – Ashok Khoja Jul 08 '21 at 16:18
  • this code give error as: OSError: [Errno 22] Invalid argument: 'C:\\Users\\Ashok Khoja\\PycharmProjects\\Learn\\"C:\\Users\\Ashok Khoja\\Desktop\\1.txt"' – Ashok Khoja Jul 08 '21 at 16:19
  • Please [edit] your question instead of adding comments. Code is unreadable in comments, and comments are usually shown in order of votes, not chronologically. Make it easy to help you by putting all the information in one place: the question. – Robert Jul 08 '21 at 16:57
  • No special handling is required to deal with Windows paths on Windows. You're likely entering the wrong path, or not running in the directory you think you are. – user2357112 Jul 09 '21 at 04:30
  • (And if you're *not* on Windows, then trying to use Windows paths makes no sense.) – user2357112 Jul 09 '21 at 04:31

2 Answers2

-1

Use C:\\desktop\\file.txt instead of C:\desktop\file.txt.

-1

The error is due to the fact that python is recognizing '\f' in 'C:\desktop\file.txt' as the form feed escape sequence.

enter image description here

It can simply be resolved by using forward slash '/' instead of backslash while providing input.

  • But user can put any input, can we handle that case? for example in windows if we copy as path it copy with '\' in path – Ashok Khoja Jul 09 '21 at 06:52
  • Use the following code: import pathlib path = pathlib.Path(input()) I tried this and it handles both the slashes (forward and backward). – Pranshu Mittal Jul 11 '21 at 05:42