Python 将文件读入列表并去除换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19062574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read file into list and strip newlines
提问by user2806298
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 \nas the thing to strip on, but I can't get it to work correctly.
我在将文件读入列表时遇到问题,当我这样做时,它只会从整个文件中创建一个项目,而不是将每个元素读入自己的字段。我正在\n用作要脱掉的东西,但我无法让它正常工作。
temp = open('drugs')
drugs = [temp.read().strip("\n")]
temp.close
Result:
结果:
['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'
采纳答案by 9000
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:
file.read()读取整个文件的内容,除非您指定最大长度。你必须是什么意思是.readlines()。但是你可以通过列表理解来更加地道:
with open('drugs') as temp_file:
drugs = [line.rstrip('\n') for line in temp_file]
The withstatement will take care of closing the file.
该with语句将负责关闭文件。
回答by Chad Skeeters
This incorporates the strip directly into the forstatement.
这将条带直接合并到for语句中。
with open('drugs', 'r') as f:
for line in map(lambda line: line.rstrip('\n'), f):
print line
Or, if you know you don't need any space before or after text on a line, you can use this.
或者,如果您知道在一行文本之前或之后不需要任何空格,则可以使用它。
import string
with open('drugs', 'r') as f:
for line in map(string.strip, f):
print line
回答by Boris
If you're okay with reading the entire file's contents into memory, you can also use str.splitlines()
如果您可以将整个文件的内容读入内存,您还可以使用 str.splitlines()
with open('your_file.txt') as f:
lines = f.read().splitlines()
splitlines()is similar to split('\n')but if your file ends with a newline, split('\n')will return an empty string at the very end, whereas splitlines()handles this case the way you want.
splitlines()类似于split('\n')但如果您的文件以换行符结尾,split('\n')将在最后返回一个空字符串,而splitlines()以您想要的方式处理这种情况。

