Easiest way to read/write a file's content in Python

后端 未结 9 2125
走了就别回头了
走了就别回头了 2020-12-01 17:32

In Ruby you can read from a file using s = File.read(filename). The shortest and clearest I know in Python is

with open(filename) as f:
    s =          


        
相关标签:
9条回答
  • 2020-12-01 18:26
    contents = open(filename)
    

    This gives you generator so you must save somewhere the values though, or

    contents = [line for line in open(filename)]
    

    This does the saving to list explicit close is not then possible (at least with my knowledge of Python).

    0 讨论(0)
  • 2020-12-01 18:27

    Slow, ugly, platform-specific... but one-liner ;-)

    import subprocess
    
    contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]
    
    0 讨论(0)
  • 2020-12-01 18:29

    Simple like that:

        f=open('myfile.txt')
        s=f.read()
        f.close()
    

    And do whatever you want with the content "s"

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