文件操作:列表,删除`\ n`s

时间:2017-10-27 16:24:21

标签: python

代码:

with open ("Test1_Votes.txt", 'r'):
    f = open("Test1_Votes.txt")
    lines = f.readlines()
    print(lines[0])
    print(lines[1])
    all_lines = []

    lines = lines.rstrip("\n") #does not work
    for line in lines:
        #in here
        all_lines.append(line)
    print(all_lines)

现在它打印输出类似于:     [' 1,2,3,0,0 \ n',...]     我希望它输出[[1,2,3,0,0,...]

档案样本:

1,2,3,0,0

1,3,2,0,0

2,3,1,0,0

3,0,1,2,0

3,0,1,0,2

零必须保留在那里,并且.txt中每一行之间没有空行

有任何建议/答案吗?

提前致谢

5 个答案:

答案 0 :(得分:5)

您的代码中有一些小问题。 with上下文打开文件,因此您不需要第二个open语句。 lines是文件中每一行的列表,包括尾随的'\n'字符,要删除它们,您可以遍历lines列表并删除换行符。

with open("Test1_Votes.txt", 'r') as f:
    lines = [line.rstrip() for line in f.readlines()]
    print(lines[0])
    print(lines[1])

答案 1 :(得分:3)

您目前仅从文件的最后一行(如果有)剥离新行字符。你应该从每一行中删除:

with open ("Test1_Votes.txt") as f:
    all_lines = []
    for line in f: 
        line = line.rstrip("\n")                  # strip new line character
        lst = [int(x) for x in line.split(',')]   # split line and cast to int
        all_lines.append(lst)

当然,您可以将整个逻辑放入列表理解中:

with open ("Test1_Votes.txt") as f:
    all_lines = [[int(x) for x in l.rstrip("\n").split(',')] for l in f]

答案 2 :(得分:1)

试试这个

fle=open("infile.txt", "r")
lst=fle.readlines()
lst=[i.strip() for i in lst]
for i in lst:

    print i
print lst

答案 3 :(得分:0)

使用re.split()代替readlines()

import re

your_file='abc def\nghi jkl\nmno pqr...'
all_lines=re.split('\n', your_file)

答案 4 :(得分:0)

单行内容可能如下所示:

all_lines = list([int(x) for x in line.replace('\n', '').split(',')] for line in open ("filepath", 'r').readlines())
print(all_lines)