如何在python中一行编写此代码
我不知道为什么您会关心代码中物理行的数量,但这里有一些非常简洁的内容(请随意编辑任何空行) 或者,这里是另一个版本:如何在python中一行编写此代码,python,Python,我不知道为什么您会关心代码中物理行的数量,但这里有一些非常简洁的内容(请随意编辑任何空行) 或者,这里是另一个版本: 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.rea
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."
Python的
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 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."
一行-
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."
提示:
将所有这些代码写在一行中会降低其可读性。
但是,python支持代码>作为行终止符
所以你可以这样做:
with open(from_file) as in, open(to_file, 'w') as o: o.write(in.read())
但请记住python的冒号:
运算符的优先级高于代码>。因此,如果我们写-
print foo(); print bar(); print baz();
这里要么执行所有打印语句,要么不执行任何语句。为什么要求写在一行中?是否希望input\u file=open(file\u name).read()
?仅仅因为您可以在一行中写入它并不意味着这样做是一个好主意。可读性往往胜过聪明。任何python代码都可以在同一行上用冒号连接,但要点是不能。Python是一种以可读性为荣的语言,但这样做并没有抓住要点:(我认为这里真正的问题是一种措辞拙劣的尝试,“有没有一种内在的方法可以做到这一点?”在这里问这个问题仍然不是一个好问题,除此之外,这是一个糟糕的提问方式,但我认为这正是OP在问这个问题时真正想要的。我知道这里面的提示很奇怪,所以我可能是错的,但我想这就是这里的意图。
print foo(); print bar(); print baz();
if True: print foo(); print bar();