如何重定向“打印”输出到文件?

发布于 2024-11-30 17:57:36 字数 1001 浏览 2 评论 0原文

我想使用 Python 将打印重定向到 .txt 文件。我有一个 for 循环,它将打印每个 .bam 文件的输出,而我想将所有输出重定向到一个文件。所以我尝试将:

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

放在脚本的开头。但是我在 .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/xxx/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!'

那么问题出在哪里?除了这个 sys.stdout 之外还有其他方法吗?

我需要我的结果如下:

Filename: ERR001268.bam
Readlines finished!
Mean: 233
SD: 10
Interval is: (213, 252)

I want to redirect the print to a .txt file using Python. I have a for loop, which will print the output for each of my .bam file while I want to redirect all output to one file. So I tried to put:

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

at the beginning of my script. However I get nothing in the .txt file.
My script is:

#!/usr/bin/python

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

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

path= '/home/xxx/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!'

So what's the problem? Any other way besides this sys.stdout?

I need my result look like:

Filename: ERR001268.bam
Readlines finished!
Mean: 233
SD: 10
Interval is: (213, 252)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

A君 2024-12-07 17:57:36

最明显的方法是打印到文件对象:

with open('out.txt', 'w') as f:
    print('Filename:', filename, file=f)  # Python 3.x
    # print >> f, 'Filename:', filename   # Python 2.x

但是,重定向标准输出也适用于我。对于像这样的一次性脚本来说可能没问题:

import sys

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

for i in range(2):
    print('i = ', i)

sys.stdout = orig_stdout
f.close()

从 Python 3.4 开始,有一个简单的上下文管理器可以用来执行此操作 在标准库中

from contextlib import redirect_stdout

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')

从 shell 本身进行外部重定向是另一种选择,通常更可取:

./script.py > out.txt

其他问题:

脚本中的第一个文件名是什么?我没有看到它初始化。

我的第一个猜测是 glob 找不到任何 bamfile,因此 for 循环不会运行。检查该文件夹是否存在,并打印脚本中的 bamfiles。

另外,使用 os.path.join 和 os.path.basename 来操作路径和文件名。

The most obvious way to do this would be to print to a file object:

with open('out.txt', 'w') as f:
    print('Filename:', filename, file=f)  # Python 3.x
    # print >> f, 'Filename:', filename   # Python 2.x

However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:

import sys

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

for i in range(2):
    print('i = ', i)

sys.stdout = orig_stdout
f.close()

Since Python 3.4 there's a simple context manager available to do this in the standard library:

from contextlib import redirect_stdout

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')

Redirecting externally from the shell itself is another option, and often preferable:

./script.py > out.txt

Other questions:

What is the first filename in your script? I don't see it initialized.

My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.

Also, use os.path.join and os.path.basename to manipulate paths and filenames.

九八野马 2024-12-07 17:57:36

您可以使用 file 参数重定向打印(在 Python 2 中,有 >> 运算符)。

f = open(filename,'w')
print('whatever', file=f) # Python 3.x
print >>f, 'whatever'     # Python 2.x

在大多数情况下,您最好只正常写入文件。

f.write('whatever')

或者,如果您想在多个项目之间写入空格,例如 print

f.write(' '.join(('whatever', str(var2), 'etc')))

You can redirect print with the file argument (in Python 2 there was the >> operator instead).

f = open(filename,'w')
print('whatever', file=f) # Python 3.x
print >>f, 'whatever'     # Python 2.x

In most cases, you're better off just writing to the file normally.

f.write('whatever')

or, if you have several items you want to write with spaces between, like print:

f.write(' '.join(('whatever', str(var2), 'etc')))
淑女气质 2024-12-07 17:57:36

Python 2Python 3 API 参考:

print(*objects, sep=' ', end='\n', file=sys.stdout,lush=False)

file 参数必须是具有 write(string) 方法的对象;如果不存在或sys.stdout 将被使用。由于打印的参数会转换为文本字符串,因此 print() 不能与二进制模式文件对象一起使用。对于这些,请使用 file.write(...) 代替。

由于 文件对象 通常包含 write() 方法,您需要做的就是传递一个 文件对象 进入其论点。

写入/覆盖文件

with open('file.txt', 'w') as f:
    print('hello world', file=f)

写入/追加到文件

with open('file.txt', 'a') as f:
    print('hello world', file=f)

Python 2 or Python 3 API reference:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Since file object normally contains write() method, all you need to do is to pass a file object into its argument.

Write/Overwrite to File

with open('file.txt', 'w') as f:
    print('hello world', file=f)

Write/Append to File

with open('file.txt', 'a') as f:
    print('hello world', file=f)
婴鹅 2024-12-07 17:57:36

不要使用 print,使用 logging

您可以更改 sys.stdout 以指向文件,但这是一种相当笨拙且不灵活的方式来处理这个问题。不要使用 print,而是使用 logging 模块。

使用logging,您可以像stdout一样进行打印,也可以将输出写入文件。您甚至可以使用不同的消息级别(严重错误警告信息调试<例如,仅将主要问题打印到控制台,但仍将次要代码操作记录到文件中。

一个简单的示例

导入 logging,获取 logger,并设置处理级别:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # process everything, even if everything isn't printed

如果您想打印到 stdout:

ch = logging.StreamHandler()
ch.setLevel(logging.INFO) # or any other level
logger.addHandler(ch)

如果您还想写入文件(如果您只想写入文件,请跳过最后一部分):

fh = logging.FileHandler('myLog.log')
fh.setLevel(logging.DEBUG) # or any level you want
logger.addHandler(fh)

然后,无论您在何处使用 print,都可以使用 logger 方法之一:

# print(foo)
logger.debug(foo)

# print('finishing processing')
logger.info('finishing processing')

# print('Something may be wrong')
logger.warning('Something may be wrong')

# print('Something is going really bad')
logger.error('Something is going really bad')

了解有关使用更高级 的更多信息>logging 功能,阅读优秀的Python 文档中的日志记录教程

Don't use print, use logging

You can change sys.stdout to point to a file, but this is a pretty clunky and inflexible way to handle this problem. Instead of using print, use the logging module.

With logging, you can print just like you would to stdout, or you can also write the output to a file. You can even use the different message levels (critical, error, warning, info, debug) to, for example, only print major issues to the console, but still log minor code actions to a file.

A simple example

Import logging, get the logger, and set the processing level:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # process everything, even if everything isn't printed

If you want to print to stdout:

ch = logging.StreamHandler()
ch.setLevel(logging.INFO) # or any other level
logger.addHandler(ch)

If you want to also write to a file (if you only want to write to a file skip the last section):

fh = logging.FileHandler('myLog.log')
fh.setLevel(logging.DEBUG) # or any level you want
logger.addHandler(fh)

Then, wherever you would use print use one of the logger methods:

# print(foo)
logger.debug(foo)

# print('finishing processing')
logger.info('finishing processing')

# print('Something may be wrong')
logger.warning('Something may be wrong')

# print('Something is going really bad')
logger.error('Something is going really bad')

To learn more about using more advanced logging features, read the excellent logging tutorial in the Python docs.

一个人的旅程 2024-12-07 17:57:36

这非常有效:

import sys
sys.stdout=open("test.txt","w")
print ("hello")
sys.stdout.close()

现在 hello 将被写入 test.txt 文件。确保使用 close 关闭 stdout,否则内容将不会保存在文件中

This works perfectly:

import sys
sys.stdout=open("test.txt","w")
print ("hello")
sys.stdout.close()

Now the hello will be written to the test.txt file. Make sure to close the stdout with a close, without it the content will not be save in the file

叹梦 2024-12-07 17:57:36

最简单的解决方案不是通过Python;而是通过Python。它穿过外壳。从文件的第一行 (#!/usr/bin/python) 我猜测您使用的是 UNIX 系统。只需像平常一样使用 print 语句,并且根本不要在脚本中打开该文件。当您要运行文件时,不要

./script.py

运行文件,而是使用

./script.py > <filename>

替换为您希望输出进入的文件的名称。 > 标记告诉(大多数)shell 将 stdout 设置为以下标记描述的文件。

这里需要提到的一件重要的事情是“script.py”需要成为可执行文件才能运行。

所以在运行./script.py之前,执行这个命令

chmod a+x script.py
(使脚本对所有用户可执行)

The easiest solution isn't through python; its through the shell. From the first line of your file (#!/usr/bin/python) I'm guessing you're on a UNIX system. Just use print statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of

./script.py

to run the file, use

./script.py > <filename>

where you replace <filename> with the name of the file you want the output to go in to. The > token tells (most) shells to set stdout to the file described by the following token.

One important thing that needs to be mentioned here is that "script.py" needs to be made executable for ./script.py to run.

So before running ./script.py,execute this command

chmod a+x script.py
(make the script executable for all users)

蒲公英的约定 2024-12-07 17:57:36

如果您使用 Linux,我建议您使用 tee 命令。实现是这样的:

python python_file.py | tee any_file_name.txt

如果您不想更改代码中的任何内容,我认为这可能是最好的解决方案。您也可以实现记录器,但需要对代码进行一些更改。

If you are using Linux I suggest you to use the tee command. The implementation goes like this:

python python_file.py | tee any_file_name.txt

If you don't want to change anything in the code, I think this might be the best possible solution. You can also implement logger but you need do some changes in the code.

纸伞微斜 2024-12-07 17:57:36

您可能不喜欢这个答案,但我认为这是正确的。除非绝对必要,否则不要更改您的标准输出目的地(也许您正在使用仅输出到标准输出的库???显然不是这里的情况)。

我认为作为一个好习惯,您应该提前将数据准备为字符串,然后打开文件并立即写入整个内容。这是因为输入/输出操作打开文件句柄的时间越长,该文件就越有可能发生错误(文件锁定错误、I/O 错误等)。只需在一次操作中完成所有操作,就不会出现什么时候可能出错的问题。

这是一个示例:

out_lines = []
for bamfile in bamfiles:
    filename = bamfile.split('/')[-1]
    out_lines.append('Filename: %s' % filename)
    samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile],
                                  stdout=subprocess.PIPE,bufsize=1)
    linelist= samtoolsin.stdout.readlines()
    print 'Readlines finished!'
    out_lines.extend(linelist)
    out_lines.append('\n')

然后,当您完成每个列表项一行的“数据行”收集后,您可以使用一些 '\n' 字符将它们连接起来,以使整个内容可输出;甚至可能将您的输出语句包装在 with 块中,以提高安全性(即使出现问题也会自动关闭您的输出句柄):

out_string = '\n'.join(out_lines)
out_filename = 'myfile.txt'
with open(out_filename, 'w') as outf:
    outf.write(out_string)
print "YAY MY STDOUT IS UNTAINTED!!!"

但是,如果您有大量数据要写入,您可以一次写一篇。我认为这与您的应用程序无关,但这是替代方案:

out_filename = 'myfile.txt'
outf = open(out_filename, 'w')
for bamfile in bamfiles:
    filename = bamfile.split('/')[-1]
    outf.write('Filename: %s' % filename)
    samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile],
                                  stdout=subprocess.PIPE,bufsize=1)
    mydata = samtoolsin.stdout.read()
    outf.write(mydata)
outf.close()

You may not like this answer, but I think it's the RIGHT one. Don't change your stdout destination unless it's absolutely necessary (maybe you're using a library that only outputs to stdout??? clearly not the case here).

I think as a good habit you should prepare your data ahead of time as a string, then open your file and write the whole thing at once. This is because input/output operations are the longer you have a file handle open, the more likely an error is to occur with this file (file lock error, i/o error, etc). Just doing it all in one operation leaves no question for when it might have gone wrong.

Here's an example:

out_lines = []
for bamfile in bamfiles:
    filename = bamfile.split('/')[-1]
    out_lines.append('Filename: %s' % filename)
    samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile],
                                  stdout=subprocess.PIPE,bufsize=1)
    linelist= samtoolsin.stdout.readlines()
    print 'Readlines finished!'
    out_lines.extend(linelist)
    out_lines.append('\n')

And then when you're all done collecting your "data lines" one line per list item, you can join them with some '\n' characters to make the whole thing outputtable; maybe even wrap your output statement in a with block, for additional safety (will automatically close your output handle even if something goes wrong):

out_string = '\n'.join(out_lines)
out_filename = 'myfile.txt'
with open(out_filename, 'w') as outf:
    outf.write(out_string)
print "YAY MY STDOUT IS UNTAINTED!!!"

However if you have lots of data to write, you could write it one piece at a time. I don't think it's relevant to your application but here's the alternative:

out_filename = 'myfile.txt'
outf = open(out_filename, 'w')
for bamfile in bamfiles:
    filename = bamfile.split('/')[-1]
    outf.write('Filename: %s' % filename)
    samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile],
                                  stdout=subprocess.PIPE,bufsize=1)
    mydata = samtoolsin.stdout.read()
    outf.write(mydata)
outf.close()
木落 2024-12-07 17:57:36

如果重定向 stdout 可以解决您的问题,Gringo Suave 的答案 很好地演示了如何操作它。

为了使它更容易,我使用 制作了一个版本contextmanagers 使用 with 语句获得简洁的通用调用语法:

from contextlib import contextmanager
import sys

@contextmanager
def redirected_stdout(outstream):
    orig_stdout = sys.stdout
    try:
        sys.stdout = outstream
        yield
    finally:
        sys.stdout = orig_stdout

要使用它,您只需执行以下操作(源自 Suave 的示例):

with open('out.txt', 'w') as outfile:
    with redirected_stdout(outfile):
        for i in range(2):
            print('i =', i)

它对于选择性重定向很有用print 当模块以您不喜欢的方式使用它时。唯一的缺点(这在很多情况下都是破坏因素)是,如果想要多个线程具有不同的 stdout 值,那么它就不起作用,但这需要一种更好、更通用的方法:间接模块使用权。您可以在这个问题的其他答案中看到它的实现。

If redirecting stdout works for your problem, Gringo Suave's answer is a good demonstration for how to do it.

To make it even easier, I made a version utilizing contextmanagers for a succinct generalized calling syntax using the with statement:

from contextlib import contextmanager
import sys

@contextmanager
def redirected_stdout(outstream):
    orig_stdout = sys.stdout
    try:
        sys.stdout = outstream
        yield
    finally:
        sys.stdout = orig_stdout

To use it, you just do the following (derived from Suave's example):

with open('out.txt', 'w') as outfile:
    with redirected_stdout(outfile):
        for i in range(2):
            print('i =', i)

It's useful for selectively redirecting print when a module uses it in a way you don't like. The only disadvantage (and this is the dealbreaker for many situations) is that it doesn't work if one wants multiple threads with different values of stdout, but that requires a better, more generalized method: indirect module access. You can see implementations of that in other answers to this question.

誰認得朕 2024-12-07 17:57:36

这是我用来打印到文件/日志的另一种方法...修改内置打印函数,以便它使用当前时间戳记录到临时目录中的文件,并打印到标准输出。在脚本中执行此操作的唯一真正优点是不必去修改现有的打印语句。

print('test')
test

将原始打印函数复制到新变量

og_print = print
og_print('test2')
test2

覆盖现有打印函数

def print(*msg):
    '''print and log!'''
    # import datetime for timestamps
    import datetime as dt
    # convert input arguments to strings for concatenation
    message = []
    for m in msg:
        message.append(str(m))
    message = ' '.join(message)
    # append to the log file
    with open('/tmp/test.log','a') as log:
        log.write(f'{dt.datetime.now()} | {message}\n')
    # print the message using the copy of the original print function to stdout
    og_print(message)
print('test3')
test3

显示文件

cat /tmp/test.log
2022-01-25 10:19:11.045062 | test3

删除文件

rm /tmp/test.log

Here's another method I've used for printing to a file/log... Modify the built-in print function so that it logs to a file in the temp directory with the current time stamp, as well as print to stdout. The only real advantage to doing this within a script is not having to go and modify existing print statements.

print('test')
test

Copy original print function to new variable

og_print = print
og_print('test2')
test2

Overwrite existing print function

def print(*msg):
    '''print and log!'''
    # import datetime for timestamps
    import datetime as dt
    # convert input arguments to strings for concatenation
    message = []
    for m in msg:
        message.append(str(m))
    message = ' '.join(message)
    # append to the log file
    with open('/tmp/test.log','a') as log:
        log.write(f'{dt.datetime.now()} | {message}\n')
    # print the message using the copy of the original print function to stdout
    og_print(message)
print('test3')
test3

display file

cat /tmp/test.log
2022-01-25 10:19:11.045062 | test3

remove file

rm /tmp/test.log
临走之时 2024-12-07 17:57:36

我可以使用以下方法破解这个问题。它将使用此打印函数而不是内置打印函数并将内容保存到文件中。

from __future__ import print_function
import builtins as __builtin__

log = open("log.txt", "a")

def print(*args):
    newLine = ""
    for item in args:
        newLine = newLine + str(item) + " "
    newLine = (
        newLine
        + """
"""
    )
    log.write(newLine)
    log.flush()
    __builtin__.print(*args)
    return

I am able to crack this using the following method. It will use this print function instead of builtin print function and save the content to a file.

from __future__ import print_function
import builtins as __builtin__

log = open("log.txt", "a")

def print(*args):
    newLine = ""
    for item in args:
        newLine = newLine + str(item) + " "
    newLine = (
        newLine
        + """
"""
    )
    log.write(newLine)
    log.flush()
    __builtin__.print(*args)
    return
圈圈圆圆圈圈 2024-12-07 17:57:36

更改 sys.stdout 的值确实会更改所有打印调用的目的地。如果您使用其他方法来更改打印目的地,您将得到相同的结果。

您的错误在其他地方:

  • 它可能在您为问题删除的代码中(调用打开的文件名从哪里来?)
  • 也可能是您没有等待数据被刷新:如果您在在终端中,数据会在每个新行后刷新,但如果打印到文件,则仅当 stdout 缓冲区已满(大多数系统上为 4096 字节)时才会刷新数据。

Changing the value of sys.stdout does change the destination of all calls to print. If you use an alternative way to change the destination of print, you will get the same result.

Your bug is somewhere else:

  • it could be in the code you removed for your question (where does filename come from for the call to open?)
  • it could also be that you are not waiting for data to be flushed: if you print on a terminal, data is flushed after every new line, but if you print to a file, it's only flushed when the stdout buffer is full (4096 bytes on most systems).
不忘初心 2024-12-07 17:57:36

在 python 3 中,您可以重新分配 print

#!/usr/bin/python3

def other_fn():
    #This will use the print function that's active when the function is called
    print("Printing from function")

file_name = "test.txt"
with open(file_name, "w+") as f_out:
    py_print = print #Need to use this to restore builtin print later, and to not induce recursion
   
    print = lambda out_str : py_print(out_str, file=f_out)
    
    #If you'd like, for completeness, you can include args+kwargs
    print = lambda *args, **kwargs : py_print(*args, file=f_out, **kwargs)
    
    print("Writing to %s" %(file_name))

    other_fn()  #Writes to file

    #Must restore builtin print, or you'll get 'I/O operation on closed file'
    #If you attempt to print after this block
    print = py_print

print("Printing to stdout")
other_fn() #Writes to console/stdout

请注意,other_fn 中的 print 仅切换输出,因为 print 正在被转换。在全局范围内重新分配。如果我们在函数内分配printother_fn中的print通常不会受到影响。如果我们想影响所有 print 调用,我们可以使用 global 关键字:

import builtins

def other_fn():
    #This will use the print function that's active when the function is called
    print("Printing from function")

def main():
    global print #Without this, other_fn will use builtins.print
    file_name = "test.txt"
    with open(file_name, "w+") as f_out:

        print = lambda *args, **kwargs : builtins.print(*args, file=f_out, **kwargs)

        print("Writing to %s" %(file_name))

        other_fn()  #Writes to file

        #Must restore builtin print, or you'll get 'I/O operation on closed file'
        #If you attempt to print after this block
        print = builtins.print

    print("Printing to stdout")
    other_fn() #Writes to console/stdout

就个人而言,我更愿意回避使用 print 函数的要求通过将输出文件描述符烘焙到一个新函数中:

file_name = "myoutput.txt"
with open(file_name, "w+") as outfile:
    fprint = lambda pstring : print(pstring, file=outfile)
    print("Writing to stdout")
    fprint("Writing to %s" % (file_name))

In python 3, you can reassign print:

#!/usr/bin/python3

def other_fn():
    #This will use the print function that's active when the function is called
    print("Printing from function")

file_name = "test.txt"
with open(file_name, "w+") as f_out:
    py_print = print #Need to use this to restore builtin print later, and to not induce recursion
   
    print = lambda out_str : py_print(out_str, file=f_out)
    
    #If you'd like, for completeness, you can include args+kwargs
    print = lambda *args, **kwargs : py_print(*args, file=f_out, **kwargs)
    
    print("Writing to %s" %(file_name))

    other_fn()  #Writes to file

    #Must restore builtin print, or you'll get 'I/O operation on closed file'
    #If you attempt to print after this block
    print = py_print

print("Printing to stdout")
other_fn() #Writes to console/stdout

Note that the print from other_fn only switches outputs because print is being reassigned in the global scope. If we assign print within a function, the print in other_fn is normally not affected. We can use the global keyword if we want to affect all print calls:

import builtins

def other_fn():
    #This will use the print function that's active when the function is called
    print("Printing from function")

def main():
    global print #Without this, other_fn will use builtins.print
    file_name = "test.txt"
    with open(file_name, "w+") as f_out:

        print = lambda *args, **kwargs : builtins.print(*args, file=f_out, **kwargs)

        print("Writing to %s" %(file_name))

        other_fn()  #Writes to file

        #Must restore builtin print, or you'll get 'I/O operation on closed file'
        #If you attempt to print after this block
        print = builtins.print

    print("Printing to stdout")
    other_fn() #Writes to console/stdout

Personally, I'd prefer sidestepping the requirement to use the print function by baking the output file descriptor into a new function:

file_name = "myoutput.txt"
with open(file_name, "w+") as outfile:
    fprint = lambda pstring : print(pstring, file=outfile)
    print("Writing to stdout")
    fprint("Writing to %s" % (file_name))
谈场末日恋爱 2024-12-07 17:57:36

我过去用来输出一些字典的东西如下:

# sample dictionary
the_dict = {'a': 'no', 'c': 'yes', 'b': 'try again'}

# path to output to
dict_path = "D:/path.txt"

# script to output file
with open(dict_path, "w") as f:
    for idx, data in the_dict.items():
        print(idx, data, file=f)

输出的文件如下所示:

a no
c yes
b try again

Something that I have used in the past to output some dictionaries is the following:

# sample dictionary
the_dict = {'a': 'no', 'c': 'yes', 'b': 'try again'}

# path to output to
dict_path = "D:/path.txt"

# script to output file
with open(dict_path, "w") as f:
    for idx, data in the_dict.items():
        print(idx, data, file=f)

The outputted file will look something like below:

a no
c yes
b try again
深海不蓝 2024-12-07 17:57:36

扩展循环打印功能的东西

x = 0
while x <=5:
    x = x + 1
    with open('outputEis.txt', 'a') as f:
        print(x, file=f)
    f.close()

Something to extend print function for loops

x = 0
while x <=5:
    x = x + 1
    with open('outputEis.txt', 'a') as f:
        print(x, file=f)
    f.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文