[英]Read file and copy to standard output.
I'm trying to write a python program that will read input and copy it to standard output (with no alterations). 我正在尝试编写一个python程序,它将读取输入并将其复制到标准输出(没有任何更改)。 I've been told that it needs to operate as a Python version of the Unix cat function.
我被告知它需要作为Unix cat函数的Python版本运行。 If a file cannot be opened, an error message needs to be printed, and then the program needs to continue processing any additional files.
如果无法打开文件,则需要打印错误消息,然后程序需要继续处理任何其他文件。 I am a complete beginner, and have tried my best to scrape something together with my limited knowledge.
我是一个完全的初学者,并且尽我所能用我有限的知识来榨取一些东西。 Here is what I have so far:
这是我到目前为止:
from sys import argv, stdout, stdin, stderr
if len(argv) == 1:
try:
stdout.write(raw_input(' ') + '\n')
except:
stderr.write ('sorry' + '\n')
quit()
else:
for filename in argv[1:]:
try:
filehandle + open(filename)
except IOError:
stderr.write('Sorry, could not open', filename + '\n')
continue
f = filehandle.read()
stdout.write(f)
I am not quite sure where to go from here.. does anyone have any advice/am I on the right track even a little bit? 我不太确定从哪里开始..有没有人有任何建议/我是否在正确的轨道上甚至一点点? Please and thank you!
谢谢,麻烦您了!
This function will copy the specified file to the console line by line (in case you later on decide to give it the ability to use the -n
command line option of cat) 此函数将指定的文件逐行复制到控制台(以防您稍后决定使其能够使用cat的
-n
命令行选项)
def catfile(fn):
with open(fn) as f:
for line in f:
print line,
It can be called with the filename once you have established the file exists. 一旦建立文件存在,就可以使用文件名调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.