Python 将变量转换为文本文件
我对Python非常陌生,我正在尝试使用用户输入写入文本文件,我遇到以下错误:Python 将变量转换为文本文件,python,Python,我对Python非常陌生,我正在尝试使用用户输入写入文本文件,我遇到以下错误: Traceback (most recent call last): File "C:/Users/Tvanderb/PycharmProjects/Text Files/Add Writing.py", line 3, in <module> import _io.TextIOWrapper ModuleNotFoundError: No module named '_io.Text
Traceback (most recent call last):
File "C:/Users/Tvanderb/PycharmProjects/Text Files/Add Writing.py", line 3, in <module>
import _io.TextIOWrapper
ModuleNotFoundError: No module named '_io.TextIOWrapper'; '_io' is not a package
我刚刚发现如何做我想做的事:
text = input("Enter Text: ")
with open('File2.txt', 'r') as x:
file = x.read()
with open('File2.txt', 'w') as x:
if file == '':
x.write(text)
else:
x.write(file + '\n')
x.write(text)
首先,您根本没有使用
io
和string
包;您可以删除这些行
其次,您正试图将文件描述符写入输出文件。也许你是说
with open('File2.txt', 'w') as x:
x.write(text + '\n')
这些有助于消除您的困惑吗?使用标准库,您可以非常轻松地做到这一点,如下所示:
text_to_write=input('Type text here:')
with open('myfile.txt','w') as file:
file.write(text+'\n')
将
与open一起使用
意味着以后不应关闭该文件。这是自动处理的,是的。我想编写文件和用户输入,这样它就可以添加我在第二次编辑中发现的文本。
text_to_write=input('Type text here:')
with open('myfile.txt','w') as file:
file.write(text+'\n')