简体   繁体   English

读取文件并复制到标准输出。

[英]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.

相关问题 Python-线程化pyinotify输出。 更好地写入文件或字符串 - Python - threaded pyinotify output. Better to write to file or to a string Python:读取多个源txt文件,按条件复制到1个输出文件中 - Python: read multiple source txt files, copy by criteria into 1 output file 将标准错误直接指向同一文件和标准输出? - direct standard error to same file and standard output? 难以理解LSTM输出。 - Trouble understanding LSTM output. 用于识别和重新格式化文件的 Python 代码示例不会生成 output。 文件名可能有问题 - Python code example for identifying and reformatting files does not generate output. File names may be a problem 在 output 上创建一个字符串。 output 是 NoneType object - Create a string on the output. The output is a NoneType object Python发布输出。 字符串操作 - Python issues output. String manipulation Codeeval挑战未返回正确的输出。 (蟒蛇) - Codeeval Challenge not returning correct output. (Python) 解析器返回“ \\ n”而不是所需的输出。 - Parser returns “\n” instead of desired output. 如何在传递字符串值并接受/存储它作为输出返回的字符串的同时从 python 执行用 C 编写的文件。 (Linux) - How to execute a file written in C from python while passing it string values and accepting/storing the string it returns as output.(Linux)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM