笨办法学python 文本复制

Posted junkdog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了笨办法学python 文本复制相关的知识,希望对你有一定的参考价值。

本来面目

from sys import argv
from os.path import exists

script, from_file, to_file = argv

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

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

print(f"The input file is {len(indata)} bytes long")
print("Ready, hit the RETURN to countinue, 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()

技术分享图片

技术分享图片

第一次简化

in_file =open(from_file)
indata = in_file.read()

合为 indata = open(from_file).read()

from sys import argv
from os.path import exists

script, from_file, to_file = argv

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

#we could do these two on noe line, how?
indata = open(from_file).read()

print(f"The input file is {len(indata)} bytes long")
print("Ready, hit the RETURN to countinue, CTRL_c to abort")
input()

out_file = open(to_file,‘w‘)
out_file.write(indata)
#open(to_file,‘w‘).write(open(from_file).read())
print("Alright, all done.")

out_file.close()
in_file.close()

技术分享图片

会报错,因为写了 indata = open(from_file).read() 就无序写关闭语句in_file.close()
以为其中的read一旦运行,文件就会被Python关闭掉

from sys import argv
from os.path import exists

script, from_file, to_file = argv

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

#we could do these two on noe line, how?
indata = open(from_file).read()

print(f"The input file is {len(indata)} bytes long")
print("Ready, hit the RETURN to countinue, CTRL_c to abort")
input()

out_file = open(to_file,‘w‘)
out_file.write(indata)
#open(to_file,‘w‘).write(open(from_file).read())
print("Alright, all done.")

out_file.close()

技术分享图片

改成一句话


from sys import argv
from os.path import exists

script, from_file, to_file = argv

open(to_file,‘w‘).write(open(from_file).read())

技术分享图片



以上是关于笨办法学python 文本复制的主要内容,如果未能解决你的问题,请参考以下文章

笨办法学Python3——习题6 字符串和文本

笨办法学Python

笨办法学Python

习题 5: 更多的变量和打印 | 笨办法学 Python

笨办法学Python

笨办法学Python(十六)