Pythons equivalent to PHP's file(fn, FILE

This question already has an answer here:

  • In Python, how do I read a file line-by-line into a list? 35 answers

  • When reading a file (line-by-line), usually the new line characters are appended to the end of the line, as you loop through it. If you want to get rid of them?

    with open('filename.txt', 'r') as f:
        for line in f:
            line = line.strip('n')
            #do things with the stripped line!
    

    这与(在Python中)相同:

    with open("file.txt", "r") as f:
        for line in f:
            line = line.rstrip("n")
            ...
    

    你要这个:

    with open('filename.txt', 'r') as f:
        data = [line.replace('n', '') for line in f]
    
    链接地址: http://www.djcxy.com/p/42358.html

    上一篇: 如何在Python中将行写入列表

    下一篇: pythons相当于PHP的文件(fn,FILE