笨办法学python3 ex17

from sys import argv
from os.path ipmort exists

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}")

# we cloud do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()

print(f"The input file is {len(indata)} bytes long")

print(f"Dose the output file exists? {exists(to_file)}")
print(f"Ready, hit RETURN to continue, CTRL-C to abort.")
input()

out_file = open(to_file, 'w')
out_file.write(indata)

print("Alright, all done")
out_file.close()
in_file.close()

运行参数:python3 ex17.py test17.txt new_file17.txt 在运行之前要将test17.txt文件创建好,并且将里面的内容填充好,然后才能将内容复制到新文件中
注释后的代码

from sys import argv  # 导入 sys 模块中的 argv 函数
from os.path import exists  # 导入 os.path 模块中的 exists 函数

# 获取命令行参数
script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}")

# 打开输入文件
in_file = open(from_file)
indata = in_file.read()

print(f"The input file is {len(indata)} bytes long")  # 显示输入文件的字节数

# 检查输出文件是否存在
print(f"Does the output file exist? {exists(to_file)}")
print(f"Ready, hit RETURN to continue, CTRL-C to abort.")
input()

# 打开输出文件并写入数据
out_file = open(to_file, 'w')
out_file.write(indata)

print("Alright, all done")  # 完成操作
out_file.close()  # 关闭输出文件
in_file.close()  # 关闭输入文件

indata = in_file.read() 的意思是从打开的输入文件(in_file)中读取所有的内容,并将其存储在变量 indata 中。具体来说:

in_file 是一个已经打开的文件对象,它代表了您从命令行参数中指定的输入文件。
.read() 是一个文件对象的方法,它用于读取文件中的内容。在这里,它会将整个文件的内容读取到内存中,并将其存储在变量 indata 中。

赞赏