0

I cannot figure out how to create file that does not exist. I tried following, yet I get error that file does not exist.

Please guide.

f=open('c:\Lets_Create_Malware\output.txt', 'r+') f=open('c:\Lets_Create_Malware\output.txt', 'w+') f=open('c:\Lets_Create_Malware\output.txt', 'a+') f=open('c:\Lets_Create_Malware\output.txt', 'r') f=open('c:\Lets_Create_Malware\output.txt', 'w') f=open('c:\Lets_Create_Malware\output.txt', 'a') 
2

2 Answers 2

2

Use a double backslash:

f=open('c:\\Lets_Create_Malware\\output.txt', 'w+') 

From the docs:

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

    1

    Given the exact paths you've specificed, at least some of your examples ought to have worked (unless the c:\Lets_Create_Malware path doesn't exist, which would add to the confusion by causing all of your test cases to fail).

    Backslashes aren't a problem here given your examples because the characters being modified aren't special:

    f=open('c:\Lets_Create_Malware\output.txt', 'w')

    works because \L and \o don't have special meanings and so are used literally (and the 'w' and 'a' flags will create the file if it's not already present).

    However, another path:

    f=open('c:\Lets_Create_Malware\badname.txt', 'w')

    will fail:

    IOError: [Errno 22] invalid mode ('w') or filename: 'c:\\Lets_Create_Malware\x08adname.txt'

    because the \b part of that filename gets translated as the bell character (ctrl-b or \x08).

    There are two ways to avoid this problem: either precede the string with the r raw string modifier (e.g., r'foo\bar') or ensure each backslash is escaped (\\). It's preferable to use os.path.join() from the os.path module for this purpose.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.