【发布时间】: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 中。那是正确的。现在将要写入该文件的内容转换为字符串,然后写入。您当前正在尝试将文件对象写入文件,这是不正确的。
-
好的,现在很清楚为什么在打开文件时需要该变量,真的怀疑为什么这是必要的。非常感谢您的解释