简体   繁体   English

在Python中使用write()写入文件无法正常工作

[英]Writing to file with write() in Python does not work as expected

I have a very simple script to write one line to a file if the condition is true. 如果条件为真,我有一个非常简单的脚本可将一行写入文件。 the script fulfill the condition but it is not writing the line to the file. 脚本满足条件,但未将行写入文件。 whats the problem? 有什么问题?

 #! /usr/bin/env python

 import sys
 import re
 import os
 import subprocess

 curdir = os.getcwd()

 files = os.listdir(curdir)

 newpbsname = curdir.split("/")
 GROUP = []
 for i in files:
     if i.endswith(".rst"):
         rstf.append(i)
 for G in files:
     if G.startswith("ti"):
         GROUP.append(G)

 GROUPS  = sorted(GROUP)

 num = int(GROUPS[-1][-8:-6])

 OP = open(GROUPS[-1],"r")
 filn = str(GROUPS[1][0:4]) + "%d" % (num+1) + ".group"
 OT = open(filn,"w")
 if GROUPS[-1][2] == 1 :
     A = " -O -i run0_03.in -p merged_21.prmtop -c restrt0-ti_21_%d.rst   -ref merged_21.inpcrd" % (num-1)
     print A
     OT.write(A + "\n")

You forgot to close the file. 您忘记了关闭文件。 When calling OT.write() the desired file is generated in your filesystem but it has not contents since it is not closed. 调用OT.write()将在文件系统中生成所需的文件,但由于未关闭,因此该文件没有内容。 By calling OT.close() the file is closed and its contents are written to the filesystem as shown by the following console output: 通过调用OT.close() ,文件将关闭,并将其内容写入文件系统,如以下控制台输出所示:

# init a file object in python
In [7]: f = open('foo.txt', 'w')

# write a sample string to the file object (IPython's output shows the bytes written)
In [8]: f.write('foo')
Out[8]: 3

# viewing foo.txt using cat does not deliver any contents
In [10]: cat foo.txt

# ll shows that foo.txt does not have any filesize
In [11]: ll
0 28 Aug 19:05 foo.txt

# close the file (file object) and see what happens
In [12]: f.close()

# after closing the file object f, cat delivers the desired output
In [13]: cat foo.txt
foo

# and ll shows that the filesize is three bytes
In [14]: ll
total 32
3 28 Aug 19:06 foo.txt

So the last part of your code should be something like: 因此,代码的最后一部分应类似于:

 if GROUPS[-1][2] == 1 :
     A = " -O -i run0_03.in -p merged_21.prmtop -c restrt0-ti_21_%d.rst   -ref merged_21.inpcrd" % (num-1)
     print A
     OT.write(A + "\n")
     OT.close() # added this line

However, opening and closing a file to write into seems to be kind of annoying. 但是,打开和关闭要写入的文件似乎很烦人。 Instead of using .open() and .close() you could use with open(filename, mode) as f as shown below: 除了使用.open().close()还可以将open(filename, mode) as f ,如下所示:

with open(filn,"w") as OT:
    if GROUPS[-1][2] == 1 :
        A=" -O -i run0_03.in -p merged_21.prmtop -c restrt0-ti_21_%d.rst   -ref merged_21.inpcrd" % (num-1)
        print A
        OT.write(A + "\n")

This opens the file before doing the stuff below the with open() statement and closes it automatically after the stuff is done. 这将在执行with open()语句下面的填充之前打开文件,并在填充完成后自动关闭文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM