How do I print the content of a .txt file in Python?

前端 未结 9 970
慢半拍i
慢半拍i 2020-12-13 18:28

I\'m very new to programming (obviously) and really advanced computer stuff in general. I\'ve only have basic computer knowledge, so I decided I wanted to learn more. Thus I

相关标签:
9条回答
  • 2020-12-13 19:14
    with open("filename.txt", "w+") as file:
      for line in file:
        print line
    

    This with statement automatically opens and closes it for you and you can iterate over the lines of the file with a simple for loop

    0 讨论(0)
  • 2020-12-13 19:17

    This will give you the contents of a file separated, line-by-line in a list:

    with open('xyz.txt') as f_obj:
        f_obj.readlines()
    
    0 讨论(0)
  • 2020-12-13 19:21

    to input a file:

    fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'
    

    to output this file you can do:

    for element in fin:
        print element 
    

    if the elements are a string you'd better add this before print:

    element = element.strip()
    

    strip() remove notations like this: /n

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