蟒蛇相当于PHP的文件(fn,FILE_IGNORE_NEW_LINES)

时间:2013-12-11 01:34:00

标签: python

我想在python中读取一个文件并将每个新行放入一个数组中。我知道如何在PHP中使用file(fn, FILE_IGNORE_NEW_LINES);函数和它的FILE_IGNORE_NEW_LINES参数,但我如何在Python中执行此操作?

3 个答案:

答案 0 :(得分:1)

当读取文件(逐行)时,通常将新行字符附加到行的末尾,然后循环播放它。如果你想摆脱它们?

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

答案 1 :(得分:0)

这与(在Python中)相同:

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

答案 2 :(得分:0)

你想要这个:

with open('filename.txt', 'r') as f:
    data = [line.replace('\n', '') for line in f]