Consider the program below, which purpose is to open some files, referenced by sys.argv[1] + "string"
.
import sys
def searchAndReplacePath(path):
filesToSearch = [path + "\main\file1.txt",
path + "\main\folder\file2.txt"]
for files in filesToSearch:
with open(files, 'r') as inFile:
filedata = inFile.readlines()
if __name__ == "__main__":
# sys.argv[1] -- Specify which path should be used
searchAndReplacePath(sys.argv[1])
At execution (Python 3.6, Windows 7) I receive an error:
Traceback (most recent call last):
File "searchAndReplacePath.py", line 35, in <module>
searchAndReplacePath(sys.argv[1])
File "searchAndReplacePath.py", line 19, in searchAndReplacePath
with open(file, 'r') as inFile:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\user\\main\\file1.txt'
Python adds backslashes to my backslashes! If I iterate the list and print()
each item in said list, I get "single backslashes", so I don't really know what to do. I have read a lot about raw strings
and how to use: r"path\to\file"
, but since I take my input from sys.argv[] I don't really now how to achieve the same result.
How do I open files, specified by a path provided via sys.argv[]
in Python on Windows?
\n
will produce a "new line",\t
will produce a "TAB" and so on. therefore, a string containing "\\" will print "\". Are you sure the two files exist at the specified location?filesToSearch
have multiple\f
form-feed characters, in which case the error would actually be an invalid argument since that's an invalid character in Windows filenames. Instead you show the error as a file not found for the path'C:\\Users\\user\\main\\file1.txt'
, in which the form-feed character has miraculously transmuted to an "f".