Python: printing a file to stdout

后端 未结 8 1947
眼角桃花
眼角桃花 2020-12-08 03:55

I\'ve searched and I can only find questions about the other way around: writing stdin to a file :)

Is there a quick and easy way to dump the contents of a file to s

相关标签:
8条回答
  • 2020-12-08 04:05

    you can also try this

    print ''.join(file('example.txt'))

    0 讨论(0)
  • 2020-12-08 04:05

    To improve on @bgporter's answer, with Python-3 you will probably want to operate on bytes instead of needlessly converting things to utf-8:

    >>> import shutil
    >>> import sys
    >>> with open("test.txt", "rb") as f:
    ...    shutil.copyfileobj(f, sys.stdout.buffer)
    
    0 讨论(0)
  • 2020-12-08 04:06

    If it's a large file and you don't want to consume a ton of memory as might happen with Ben's solution, the extra code in

    >>> import shutil
    >>> import sys
    >>> with open("test.txt", "r") as f:
    ...    shutil.copyfileobj(f, sys.stdout)
    

    also works.

    0 讨论(0)
  • 2020-12-08 04:09
    f = open('file.txt', 'r')
    print f.read()
    f.close()
    

    From http://docs.python.org/tutorial/inputoutput.html

    To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

    0 讨论(0)
  • 2020-12-08 04:12

    Sure. Assuming you have a string with the file's name called fname, the following does the trick.

    with open(fname, 'r') as fin:
        print(fin.read())
    
    0 讨论(0)
  • 2020-12-08 04:20

    You can try this.

    txt = <file_path>
    txt_opn = open(txt)
    print txt_opn.read()
    

    This will give you file output.

    0 讨论(0)
提交回复
热议问题