相关疑难解决方法(0)

如何使用python将'print'输出重定向到文件?

我想使用python将打印重定向到.txt文件.我有一个'for'循环,它会'打印'我的每个.bam文件的输出,而我想将所有这些输出重定向到一个文件.所以我试着把

 f = open('output.txt','w'); sys.stdout = f
Run Code Online (Sandbox Code Playgroud)

在我的脚本开头.但是我在.txt文件中什么都没得到.我的脚本是:

#!/usr/bin/python

import os,sys
import subprocess
import glob
from os import path

f = open('output.txt','w')
sys.stdout = f

path= '/home/xug/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')

for bamfile in bamfiles:
    filename = bamfile.split('/')[-1]
    print 'Filename:', filename
    samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile],
                                  stdout=subprocess.PIPE,bufsize=1)
    linelist= samtoolsin.stdout.readlines()
    print 'Readlines finished!'
    ........print....
    ........print....
Run Code Online (Sandbox Code Playgroud)

所以有什么问题?除了这个sys.stdout之外的任何其他方式?

我需要我的结果如下:

Filename: ERR001268.bam
Readlines finished!
Mean: 233
SD: 10
Interval is: (213, 252)
Run Code Online (Sandbox Code Playgroud)

python file-writing

151
推荐指数
8
解决办法
50万
查看次数

如何将python屏幕输出保存到文本文件

我是Python的新手。我需要从字典查询项目并将结果保存到文本文件。这是我所拥有的:

import json
import exec.fullog as e

input = e.getdata() #input now is a dict() which has items, keys and values.

#Query

print 'Data collected on:', input['header']['timestamp'].date()
print '\n CLASS 1 INFO\n'

for item in input['Demographics']:
    if item['name'] in ['Carly', 'Jane']:
        print item['name'], 'Height:', item['ht'], 'Age:', item['years']

for item in input['Activity']:
    if item['name'] in ['Cycle', 'Run', 'Swim']:
       print item['name'], 'Athlete:', item['athl_name'], 'Age:', item['years']
Run Code Online (Sandbox Code Playgroud)

如何将打印的输出保存到文本文件?

python python-2.7

2
推荐指数
5
解决办法
5万
查看次数

>>运算符在python中做什么?

我在一个项目中找到了这个代码,我不知道它的>>作用.有人有解释吗?

def save(self, fpath=None):
        """
        Save the JSON data to fpath. This is done automatically if the
        game is over.
        """
        if fpath is None:
            fpath = _jsonf % self.eid
        try:
            print >> gzip.open(fpath, 'w+'), self.rawData,
        except IOError:
            print >> sys.stderr, "Could not cache JSON data. Please " \
                                 "make '%s' writable." \
                                 % os.path.dirname(fpath)
Run Code Online (Sandbox Code Playgroud)

我知道这段代码从模块中的其他文件和对象获取信息,我知道代码的整体运作方式.只有这print >>让我感到困惑.当此模块安装在没有写访问权限的目录中时,将显示该消息Could not cache....整个文件都在这里,但我怀疑它会有所帮助.

python

2
推荐指数
1
解决办法
127
查看次数

标签 统计

python ×3

file-writing ×1

python-2.7 ×1