我有str = 'some words\n'
,我想用
with open(newfile, 'a') as the_file:
the_file.write(str)
我怎么能用'some words\n'
而不是'some words'
字面写字,最后输入?
答案 0 :(得分:2)
请尝试像str = "some words \\n"
一样翻回斜杠。
答案 1 :(得分:1)
您需要转义转义字符:
str = 'some words\n'
with open(newfile, 'a') as the_file:
str = str.replace("\n","\\n")
the_file.write(str)
答案 2 :(得分:1)
您可以使用原始字符串r'..'
构造来执行此操作,也可以使用try
catch块中的文件打开构造并在写入后关闭打开的文件描述符完整。
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')
答案 3 :(得分:0)
string = "some words\n"
with open("temp.txt", "w+") as fp:
temp = string[:-2] + r'\n'
fp.write(temp)
答案 4 :(得分:0)
您可以使用不带引号的字符串表示。它将适用于所有转义序列,而不仅仅是'\ n':
w = "some\twords\n"
repr(w)[1:-1] # some\twords\n
但引号存在问题:
w = '''single'double"quote'''
repr(w)[1:-1] # single\'double"quote