[英]Write pure string to file in python
I have str = 'some words\\n'
and i want to print it to file with 我有
str = 'some words\\n'
,我想将其打印到文件中
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? 我如何才能在末尾使用Enter直接写
'some words\\n'
而不是'some words'
?
请尝试使用doule反斜杠,例如str = "some words \\\\n"
。
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)
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. 您可以使用raw-string
r'..'
构造来做到这一点,也可以在try
catch块中使用file-open构造,并在写入完成后关闭打开的文件描述符。
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')
string = "some words\n"
with open("temp.txt", "w+") as fp:
temp = string[:-2] + r'\n'
fp.write(temp)
You could use the string representation without the quotes. 您可以使用不带引号的字符串表示形式。 It will work with all escape sequences, not only the '\\n':
它将与所有转义序列一起使用,而不仅仅是'\\ n':
w = "some\twords\n"
repr(w)[1:-1] # some\twords\n
However there is an issue with quotes: 但是引号存在问题:
w = '''single'double"quote'''
repr(w)[1:-1] # single\'double"quote
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.