从python复制并覆盖文件,然后读取它

时间:2018-10-11 17:47:10

标签: python

这是我为python写的:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print("Let's see what we have in the file we want to copy:")
open_file = open(from_file)
read_file = open_file.read()
print(read_file)

print("Now let's see what we have in the file we want to copy to:")
new_file = open(to_file)
new_read = new_file.read()
print(new_read)

print(f"Now let's copy stuff from {from_file} to {to_file}")
new_file2 = open(to_file, 'w')
new_file2.write(read_file)
new_file2.close()

print(f"Now let's see what is in {to_file}")
new_file3 = open(new_file2)
new_read2 = new_file3.read()
print(new_read2)

这是我得到的错误:

enter image description here

有人可以告诉我我究竟在这里做错了什么,还是我错过了什么?

2 个答案:

答案 0 :(得分:1)

查看您的代码:

print(f"Now let's copy stuff from {from_file} to {to_file}")
new_file2 = open(to_file, 'w')
new_file2.write(read_file)
new_file2.close()

print(f"Now let's see what is in {to_file}")
new_file3 = open(new_file2)

open需要文件名(字符串)。您给它提供了一个文件描述符。试试

new_file3 = open(to_file)

请注意,这与您要为用户打印的消息匹配。

答案 1 :(得分:0)

这将清除所有多余的“ new_file#”,并使用with open关闭文件并重新使用变量名:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print("Let's see what we have in the file we want to copy:")
with open(from_file) as open_file:
    read_file = open_file.read()
    print(read_file)

print("Now let's see what we have in the file we want to copy to:")
with open(to_file) as new_file:
    new_read = new_file.read()
    print(new_read)

print(f"Now let's copy stuff from {from_file} to {to_file}")
with open(to_file, 'w') as new_file:
    new_file.write(read_file)

print(f"Now let's see what is in {to_file}")
with open(to_file) as new_file:
    new_read = new_file.read()
    print(new_read)