Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中向新文本文件写入/打印字符串?_Python_String_File - Fatal编程技术网

如何在python中向新文本文件写入/打印字符串?

如何在python中向新文本文件写入/打印字符串?,python,string,file,Python,String,File,我在一个变量中有一个字符串,我想把这个变量以打印的形式写入一个文本文件。 我的猜测显然是这样的: 'filename'.write(string_variable) 但它给了我这个错误 Traceback (most recent call last): File "<pyshell#14>", line 1, in <module> main('studyguide.txt','decrypted.txt') File "C:/Users/Casey/Document

我在一个变量中有一个字符串,我想把这个变量以打印的形式写入一个文本文件。 我的猜测显然是这样的:

'filename'.write(string_variable)
但它给了我这个错误

Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
main('studyguide.txt','decrypted.txt')
File "C:/Users/Casey/Documents/New folder/pa11.py", line 45, in main
writefile.write(finalstr)
AttributeError: 'str' object has no attribute 'write'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
main('studyguide.txt','decrypted.txt')
文件“C:/Users/Casey/Documents/New folder/pa11.py”,第45行,主目录
writefile.write(finalstr)
AttributeError:“str”对象没有属性“write”
有什么想法吗?

你需要一个文件,然后使用
文件。写

with open(writefile, 'w') as f:
    f.write(finalstr)
打开(“文件名”,“w+”)