python将每行文本文件打印到没有\ n的列表中
我仍然是学习Python的新手,只是想知道如何将文本文件的每行存储在没有\ n出现的情况下。 我尝试过:
file = open("test_file.txt", "r")
table = [line.split(') for line in file.readlines()]
输出:
[['Beans', ' 1222', ' 422', ' 6712\n'], ['Eggs', ' 4423', ' 122', ' 2231\n'], ['Tomato', ' 2232', ' 224', ' 2321']]
所需的输出:
[['Beans', '1222', '422', '6712], ['Eggs', '4223', '122', '2231'], ['Tomato', '2232', '224', '2321']]
我尝试了temp = file.read.read()。splitlines()
,但最终将其全部存储到一个列表中['bean,1222 ,422,6712','鸡蛋,4423,122,2231','番茄,2232,224,2321']
当我仍然希望每行都是列表本身时。 任何帮助都非常感谢!
I'm still new to learning python and was just wondering how to store each line of a text file into a list without the \n appearing.
I've tried:
file = open("test_file.txt", "r")
table = [line.split(') for line in file.readlines()]
Outputs:
[['Beans', ' 1222', ' 422', ' 6712\n'], ['Eggs', ' 4423', ' 122', ' 2231\n'], ['Tomato', ' 2232', ' 224', ' 2321']]
Desired output:
[['Beans', '1222', '422', '6712], ['Eggs', '4223', '122', '2231'], ['Tomato', '2232', '224', '2321']]
I've tried temp = file.read().splitlines()
but it ends up storing it all into one list['Beans, 1222, 422, 6712', 'Eggs, 4423, 122, 2231', 'Tomato, 2232, 224, 2321']
when I still want each line to be a list itself.
Any help greatly appreciated!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就我而言,我总是使用以下行来摆脱
\ n
每次阅读文件时:在您的情况下,只需使用:
In my case, I always use following line to get rid of
\n
every time I read a file:In your case, just use:
有两个快速解决方案。
由于Yihua Zhou已经提供了一个,所以我会提供另一个。 Please note that that the strip method might remove more than you want.查看
string.strip()
在这里 。splitlines()
方法将文本分配在\ n
字符上还要注意,如果可能files, as it closes it automagically. See this for some explanation...
There's two quick solutions.
Since Yihua Zhou already provided one, I'll provide another. Please note that that the strip method might remove more than you want. Look at the docs for
string.strip()
here.The
splitlines()
method splits a text on\n
charactersAlso note that if possible, you should use the
with open()
way to open files, as it closes it automagically. See this for some explanation...看来您的输入文件实际上是一个CSV文件,在其中忽略逗号后的空格,在这种情况下,您可以使用
csv.reader
与skipinitialSpace
for更好的可读性:演示: https://replit.com/redplit.com/@blhsing/@blhsing/technicalplumpmathemathematics
It appears that your input file is in fact a CSV file where the spaces after commas are to be ignored, in which case you can use
csv.reader
with theskipinitialspace
option for better readability:Demo: https://replit.com/@blhsing/TechnicalPlumpMathematics