在Python中读取换行符分隔文件的最佳方法,并丢弃换行符? [英] Best method for reading newline delimited files in Python and discarding the newlines?

查看:1215
本文介绍了在Python中读取换行符分隔文件的最佳方法,并丢弃换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想到的是,我想到的是以下代码,包含一次性测试代码。

  import os 

def getfile(filename,results) :
f = open(filename)
filecontents = f.readlines()
在filecontents中的行:
foo = line.strip('\\\
')
result.append(foo)
返回结果

blahblah = []

getfile('/ tmp / foo',blahblah)

for x in blahblah:
print x

建议?

解决方案

  lines = open(filename).read()。splitlines()


I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.

What I've come up with is the following code, include throwaway code to test.

import os

def getfile(filename,results):
   f = open(filename)
   filecontents = f.readlines()
   for line in filecontents:
     foo = line.strip('\n')
     results.append(foo)
   return results

blahblah = []

getfile('/tmp/foo',blahblah)

for x in blahblah:
    print x

Suggestions?

解决方案

lines = open(filename).read().splitlines()

这篇关于在Python中读取换行符分隔文件的最佳方法,并丢弃换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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