将文件读入列表并删除换行符 [英] Read file into list and strip newlines

查看:75
本文介绍了将文件读入列表并删除换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将文件读入列表时遇到问题,当我这样做时,它只能从整个文件中创建一个项目,而不是将每个元素读入其自己的字段中.我正在使用\n作为要剥离的东西,但是我无法使其正常工作.

I'm having issues in reading a file into a list, When I do it only creates one item from the entire file rather than reading each element into its own field. I'm using \n as the thing to strip on, but I can't get it to work correctly.

temp = open('drugs')
drugs = [temp.read().strip("\n")]
temp.close

结果:

['40 Stimpak\n53 Mentats\n87 Buffout\n109 Rad-X\n125 Booze\n260 Jet Antidote\n311 Roentgen Rum\n424 Monument Chunk\n480 Bonus +1 Agility\n525 Hypo \n48 RadAway\n71 Fruit\n103 Iguana-on-a-stick\n110 Psycho\n144 Super Stimpak\n273 Healing Powder\n334 Poison\n469 Rot Gut\n481 Bonus +1 Intelligence \n49 Antidote\n81 Iguana-on-a-stick\n106 Nuka-Cola\n124 Beer\n259 Jet\n310 Gamma Gulp Beer\n378 Cookie\n473 Mutated Toe\n482 Bonus +1 Strength ']
drugs.strip('\n')

Traceback (most recent call last):
   File "seek", line 18, in <module>
     print drugs.strip('\n')
AttributeError: 'list' object has no attribute 'strip'

推荐答案

file.read()读取整个文件的内容,除非您指定最大长度.您必须指的是.readlines().但是您可以通过列表理解来变得更加惯用:

file.read() reads entire file's contents, unless you specify max length. What you must be meaning is .readlines(). But you can go even more idiomatic with a list comprehension:

with open('drugs') as temp_file:
  drugs = [line.rstrip('\n') for line in temp_file]

with语句将负责关闭文件.

The with statement will take care of closing the file.

这篇关于将文件读入列表并删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆