如何在 python 中向用户询问输出文件

发布于 2024-12-07 20:24:42 字数 348 浏览 0 评论 0原文

我必须向用户询问输出文件,然后将数据附加到其中,但每当我尝试时,它都会告诉我该数据没有附加属性。我认为这是因为当我尝试打开文件时,它会将其视为字符串,而不是附加数据的实际文件。我已经尝试了多种方法来执行此操作,但现在我只剩下这个:

Output_File = str(raw_input("Where would you like to save this data? "))
fileObject = open(Output_File, "a")
fileObject.append(Output, '\n')
fileObject.close()

我试图附加到它的输出只是我之前定义的列表。任何帮助将不胜感激。

I have to ask the user for an output file and then append data to it but whenever I try it tells me that the data has no append attribute. I think this is because when I try to open the file it is seeing it as a string and not an actual file to append data too. I have tried multiple ways of doing this but right now I am left with this:

Output_File = str(raw_input("Where would you like to save this data? "))
fileObject = open(Output_File, "a")
fileObject.append(Output, '\n')
fileObject.close()

The output that I am trying to append to it is just a list I earlier defined. Any help would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

宁愿没拥抱 2024-12-14 20:24:42

您的错误在这一行:

fileObject.append(Output, '\n')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'file' object has no attribute 'append'

使用文件对象的 write 方法:

fileObject.write(Output+'\n')

Your error is at this line:

fileObject.append(Output, '\n')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'file' object has no attribute 'append'

Use the write method of a file object:

fileObject.write(Output+'\n')
不弃不离 2024-12-14 20:24:42

文件对象没有 append 方法。您正在寻找write。另外,str(raw_input(...))是多余的,raw_input已经返回一个字符串。

File objects have no append method. You're looking for write. Also, str(raw_input(...)) is redundant, raw_input already returns a string.

灼痛 2024-12-14 20:24:42

该错误消息非常不言自明。这是因为文件对象没有 append 方法。您应该简单地使用 write

fileObject.write(str(Output) + '\n')

The error message is pretty self-explanatory. This is because file objects don't have append method. You should simply use write:

fileObject.write(str(Output) + '\n')
看透却不说透 2024-12-14 20:24:42
def main():
    Output = [1,2,4,4]
    Output_File = input("Where would you like to save this data?")
    fileObject = open(Output_File, 'a')
    fileObject.write(str(Output)+'\n')
    fileObject.close()
if __name__ == '__main__':
    main()

只需使用 .write 方法即可。

def main():
    Output = [1,2,4,4]
    Output_File = input("Where would you like to save this data?")
    fileObject = open(Output_File, 'a')
    fileObject.write(str(Output)+'\n')
    fileObject.close()
if __name__ == '__main__':
    main()

just use the .write method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文