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

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

问题描述

我正在尝试确定在Python中读取以换行符分隔的文件时摆脱换行符的最佳方法.

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

建议?

推荐答案

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

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

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