【问题标题】:How do I write on a file to then copy it on another file?如何在文件上写入然后将其复制到另一个文件?
【发布时间】:2021-03-19 02:38:50
【问题描述】:

目前正在学习 Python,我正在尝试编写一个 .txt 文件,然后将其复制到第二个 .txt 文件中。

from sys import argv

script, send_file, get_file = argv

in_file = open(send_file, "r+")
in_file.write("I'm sending information to the receiver file.")

open(get_file, "w")
get_file.write(f"{in_file}")

但我一直这样得到同样的错误。

Traceback (most recent call last):
  File "ex15_test.py", line 11, in <module>
    get_file.write(f"{in_file}")
AttributeError: 'str' object has no attribute 'write'

然后我将 'open(get_file, "w")' 和 'get_file.write(f"{in_file}")' 放入一个变量中并且没有任何错误。

out_file = open(get_file, "w")
out_file.write(f"{in_file}")

但这就是最终写入第二个文件的内容:

<_io.textiowrapper name="sender.txt" mode="r+" encoding="cp1252">

  • 你知道我做错了什么吗?
  • 为什么当我在第二个代码中使用变量时它会起作用?

【问题讨论】:

  • open(get_file, "w") 不会将您的变量存储在任何地方。 out_file = open(get_file, "w") 将打开您的文件并将其存储在变量 out_file 中。那是正确的。现在将要写入该文件的内容转换为字符串,然后写入。您当前正在尝试将文件对象写入文件,这是不正确的。
  • 好的,现在很清楚为什么在打开文件时需要该变量,真的怀疑为什么这是必要的。非常感谢您的解释

标签: python file text write


【解决方案1】:

open(get_file, "w")中,get_file是文件名,是一个字符串。

您需要写入文件对象,就像您在代码的第一部分中所做的那样。所以,应该是:

f = open(get_file, "w")
f.write(f"{in_file}")
f.close()

请注意,您忘记关闭代码中的两个文件。

不过,好的做法是使用上下文管理器来为您处理关闭,无论您的代码中发生什么(异常,...)

所以,最好的方法是:

with open(get_file, "w") as f:
    f.write(f"{in_file}")

【讨论】:

  • 哦,我明白了,所以我的代码中将存储文件的地方称为文件对象。这个概念现在很清楚了,我真的很感激
  • 不客气。请注意,如果您认为其中一个答案回答了您的问题,您可以接受(左侧的复选标记)。
  • 哦,是的,当然。只是我还是这个网站的新手,所以我的声誉不允许我更改公开显示,无论如何感谢您指出这一点。
【解决方案2】:

抱歉,代码混乱,但这应该可以满足我的想法

from sys import argv

script, send_file, get_file = argv

in_file = open(send_file, "r+")
in_file.write("I'm sending information to the receiver file.")
in_file.close()

in_file_2 = open(send_file, "r")
in_file_text = in_file_2.read()
in_file_2.close()

secondFile = open(get_file, "w")
secondFile.write(f"{in_file_text}")
secondFile.close()

【讨论】:

  • 天哪,这正是我想做的。我知道在代码结束时我需要关闭文件,但我没有想到以这种方式使用 close 函数。谢谢
  • 是的,对文件所做的任何更改仅在关闭文件后应用
猜你喜欢
  • 2022-01-26
  • 2016-12-28
  • 1970-01-01
  • 2011-12-06
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 2016-06-14
相关资源
最近更新 更多