'python - write to txt file. the problem: some file names are ok, some file names get error

for example:

testdata.txt - is fine

datatest.txt - fail

it happens with a lot of file names, some names are just fine a lot of other names fail.

examples on screenshots:

Code with good name:

code with good name

the result:

job done

Code with bad name:

code with bad name

the result:

error



Solution 1:[1]

Try using raw strings for your variables, r"H:\testdata.txt" and r"H:\datatest.txt" or you can escape the backslashes like so "H:\\testdata.txt" and "H:\\datatest.txt".

Solution 2:[2]

That’s because \t means ASCII tab. Use r strings instead. More info on both things on https://docs.python.org/3/reference/lexical_analysis.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luth
Solution 2 Chris