I have str = 'some words\n' and i want to print it to file with
with open(newfile, 'a') as the_file:
the_file.write(str)
how can i write literally just 'some words\n' not 'some words' with enter at the end?
You need to escape the escape character:
str = 'some words\n'
with open(newfile, 'a') as the_file:
str = str.replace("\n","\\n")
the_file.write(str)
str will change use of str's default behaviour.You can use the raw-string r'..' construct to do that, also would be nice to use the file-open constructs within the try catch blocks and close the open file descriptor once the write is complete.
try:
str = r'some words\n'
with open('newfile', 'a') as fd:
fd.write(str)
fd.close()
except IOError as e:
print('unable to open file newfile in append mode')
str = r'some words\n'. BTWstris a bad choice for a variable name, it will mask the built-instrtype.