【问题标题】:what is the pythonic way to processs "\n" in line of a file [duplicate]在文件行中处理“\ n”的pythonic方法是什么[重复]
【发布时间】:2016-08-31 00:54:58
【问题描述】:

在文件行中处理“\n”的pythonic方法是什么

readline 或 readlines 或自己替换 '\n'

示例文件(t.txt):

221.177.0.0/16  
117.128.0.0/21  
221.183.0.0/16  

当我使用下面的代码读取文件(t.py)时:

import sys
fn = sys.argv[1]
lines = list()
with open(fn) as f:
    for line in f:
        lines.append(line)
print lines

当运行脚本代码时,我得到这个输出:

python t.py t.txt 
['221.177.0.0/16\n', '117.128.0.0/21\n', '221.183.0.0/16\n']

列表中有很多“\n”。

【问题讨论】:

  • lines.append(line.strip('\n'))

标签: python


【解决方案1】:

只需在readlines 循环中使用rstrip。例如:

import sys
fn = sys.argv[1]
f = open(fn)
lines = [l.rstrip() for l in f.readlines()]
f.close()

【讨论】:

    【解决方案2】:

    或者你可以删除最后一个'\n'

        lines.append(line[:-1])
    

    这里 '\n' 被视为单个字符,因此 line[:-1] 将从 "line" 中删除尾随 ONE 字符

    【讨论】:

      【解决方案3】:

      处理文件时将其剥离。

      >>> '221.177.0.0/16\n'.rstrip('\n')
      '221.177.0.0/16'
      

      【讨论】:

        猜你喜欢
        • 2018-02-21
        • 1970-01-01
        • 2015-07-18
        • 2012-05-02
        • 2011-11-29
        • 1970-01-01
        • 1970-01-01
        • 2015-09-20
        • 1970-01-01
        相关资源
        最近更新 更多