Python 文件操作:列表,删除“%n”
代码: 现在,它打印的输出类似于: ['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中的每一行之间没有空行 有什么建议/答案吗Python 文件操作:列表,删除“%n”,python,Python,代码: 现在,它打印的输出类似于: ['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中的每一行之间没有空行 有什么建议/答案吗 提前感谢您当前仅从文件的最后一行(如果有)中删除新行字符。您应该从每一行中删除: with open ("Test1_Votes.txt", 'r'): f = open("Test1_V
提前感谢您当前仅从文件的最后一行(如果有)中删除新行字符。您应该从每一行中删除:
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)
当然,您可以将整个逻辑放入列表:
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语句。lines是文件中每一行的列表,包括尾随的“\n”字符。要删除这些字符,您可以在lines列表上迭代并删除新行字符
with open ("Test1_Votes.txt") as f:
all_lines = [[int(x) for x in l.rstrip("\n").split(',')] for l in f]
使用re.split而不是readlines:
试试这个
import re
your_file='abc def\nghi jkl\nmno pqr...'
all_lines=re.split('\n', your_file)
一行代码可能如下所示:
fle=open("infile.txt", "r")
lst=fle.readlines()
lst=[i.strip() for i in lst]
for i in lst:
print i
print lst
你能分享文件内容的样本吗?Test1_vots.txt的内容是什么?完成!我已经用它更新了问题。您不需要再次打开文件。感谢您的快速回复,它似乎工作正常,但是否有办法将每个值从字符串更改为整数?非常感谢,我可能在您编辑问题之前看到了您的问题。我通常建议您不要使用嵌套列表理解和一行程序,除非您正在使用。它们会使bug很难被发现,因为一行中发生的事情太多了。
fle=open("infile.txt", "r")
lst=fle.readlines()
lst=[i.strip() for i in lst]
for i in lst:
print i
print lst
all_lines = list([int(x) for x in line.replace('\n', '').split(',')] for line in open ("filepath", 'r').readlines())
print(all_lines)