Python 使用命令行参数将非常基本的副本从一个文件写入另一个文件
我是python新手,尝试将一个文件基本复制到另一个文件程序中。 我现在的代码是Python 使用命令行参数将非常基本的副本从一个文件写入另一个文件,python,Python,我是python新手,尝试将一个文件基本复制到另一个文件程序中。 我现在的代码是 import sys if len(sys.argv) !=3: print 'usage: filecopy source destination' else: try: infile = open(sys.argv[1]) outfile = open(sys.argv[2], 'w') except IOError: print 'so
import sys
if len(sys.argv) !=3:
print 'usage: filecopy source destination'
else:
try:
infile = open(sys.argv[1])
outfile = open(sys.argv[2], 'w')
except IOError:
print 'source file does not exist'
getline(infile, line)
infile.close()
outfile.close()
正如您所希望看到的,我正在试图输出为什么如果用户试图错误地使用程序,程序将无法工作
<>我最近写了一个C++程序,它做的和这个一样,它工作得很好,但是现在我必须把相同的逻辑转换成不同的语法。< /p> 从代码中删除不需要的空格。这可能有用 我已经编辑了你的帖子,请尝试运行此代码 您必须处理
try…除非文件不存在
import shutil
import sys
if len(sys.argv) !=3:
print 'usage: filecopy source destination'
else:
try:
shutil.copyfile(sys.argv[1], sys.argv[2])
except IOError:
print 'source file does not exist'
我试着在字符串行中写一行内嵌,然后
将其写入输出文件
不要试图用Python“编写C++”。对于手头的任务:
import sys
if len(sys.argv) !=3:
print('usage: filecopy source destination')
else:
try:
with open(sys.argv[1], 'r') as inf, open(sys.argv[2], 'w') as outf:
for line in inf:
outf.write(line)
except IOError:
print('{} does not exist or cannot be read'.format(sys.argv[1]))
刚才看到我的else缩进太多了。到底是什么问题?现在是说“elif infle.fail()”中的()有一个无效语法。你调用的函数是什么?我不确定getline是否是python中的函数,就像我说的,我习惯了C++,所以我试图把一行的代码写进字符串行,然后把它写进一个输出文件。“Traceback(最近的调用最后):文件“FielEcpp.Py”,第2行,在Fiel=打开(sys .ARGV(1))NealError:名称‘sys’没有被定义”这就是我现在遇到的错误。导入的sys
module。好的,修复了这个问题。现在是说infle=open(sys.argv[1])超出了范围。try之前的moved if条件。实际上nevermind:(它说outfile.close()中没有定义outfile的名称。那么使用'out.write(inf.read())'而不是for cycle如何?也可以工作,但在给定原始要求的情况下“将其写入字符串行,然后写入输出文件”我想展示如何在Python中具体实现这一点。
from sys import argv
def main () :
sourcefile = argv [ 1 ]
destfile = argv [ 2 ]
sourceptr = open ( sourcefile , 'r')
destptr = open ( destfile , 'w')
destptr . write ( sourceptr . read () )
sourceptr . close ()
destptr . close ()
main ()