from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
input.close()
答案 0 :(得分:1)
Python的with
语句在这里很方便。当你处理文件时,它习惯于使用它,因为它会处理掉对象并捕获异常。
您可以在documentation。
中阅读相关内容以下是您在计划中使用with
的方法:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
with open(from_file) as input, open(to_file, 'w') as output:
print "The input file is %d bytes long" % len(input.read())
print "Does the output file exist? %r" % exists(to_file)
raw_input("Ready, hit RETURN to continue, CTRL-C to abort.")
output.write(input.read())
print "Alright, all done."
单线 -
with open(from_file) as in, open(to_file, 'w') as o: o.write(in.read())
提示:
将所有这些代码写在一行中会降低其可读性。
但是,python支持;
作为行终止符。
所以你可以这样做:
print foo(); print bar(); print baz();
但请记住python的冒号:
运算符的优先级高于;
。因此,如果我们写 -
if True: print foo(); print bar();
这里要么所有的print语句都会执行,要么都不执行。
答案 1 :(得分:0)
我不知道为什么你会关心你的代码中的物理行数,但这里有一些非常简洁的东西(随意编辑任何空白行)
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
with open(from_file) as infile: indata = infile.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %s" % 'no yes'.split()[int(exists(to_file))]
raw_input("Ready, hit RETURN to continue, CTRL-C to abort.")
with open(to_file, 'w') as outfile: output.write(indata)
print "Alright, all done."
或者,这是另一个版本:
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copying from %s to %s" % (from_file, to_file)
with open(from_file) as infile, open(to_file, 'w') as outfile:
indata = infile.read()
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %s" % 'no yes'.split()[int(exists(to_file))]
raw_input("Ready, hit RETURN to continue, CTRL-C to abort.")
output.write(indata)
print "Alright, all done."