无法读取使用不同方法写入的文件的内容

时间:2019-04-05 05:28:05

标签: python

我想读取通过其他功能写入文件的文件内容

from subprocess import *
import os
def compile():
    f=open("reddy.txt","w+")
    p=Popen("gcc -c rahul.c ",stdout=f,shell=True,stderr=STDOUT) #i have even tried with with open but it is not working,It is working with r+ but it is appending to file.
    f.close()   

def run():
    p1=Popen("gcc -o r.exe rahul.c",stdout=PIPE,shell=True,stderr=PIPE)
    p2=Popen("r.exe",stdout=PIPE,shell=True,stderr=PIPE)
    print(p2.stdout.read())
    p2.kill()

compile()
f1=open("reddy.txt","w+")    
first_char=f1.readline() #unable to read here ….!!!!!!
print(first_char)

  #run()

first_char必须具有文件reddy.txt的第一行,但显示为空

2 个答案:

答案 0 :(得分:1)

您假设Popen完成了该过程,但没有完成; Popen只会启动一个进程-除非编译非常快速 ,否则当您尝试阅读时reddy.txt很可能为空它。

对于Python 3.5+,您需要subprocess.run()

# Don't import *
from subprocess import run as s_run, PIPE, STDOUT
# Remove unused import
#import os

def compile():
    # Use a context manager
    with open("reddy.txt", "w+") as f:
        # For style points, avoid shell=True
        s_run(["gcc", "-c", "rahul.c "], stdout=f, stderr=STDOUT,
            # Check that the compilation actually succeeds
            check=True)

def run():
    compile()  # use the function we just defined instead of repeating youself
    p2 = s_run(["r.exe"], stdout=PIPE, stderr=PIPE,
        # Check that the process succeeds
        check = True,
        # Decode output from bytes() to str()
        universal_newlines=True)
    print(p2.stdout)

compile()
# Open file for reading, not writing!
with open("reddy.txt", "r") as f1:
    first_char = f1.readline()
print(first_char)

(尽管您发布的任何代码中都没有使用run()函数,但我还是沿用了同样的用法。)

first_char的名称具有误导性; readline()将读取整行。如果只需要第一个字节,请尝试

first_char = f1.read(1)

如果您需要与旧版本的Python兼容,请尝试使用check_outputcheck_call而不是run。如果您使用的是3.7+版本,则可以使用text=True代替较旧的名称universal_newlines=True

有关我所做更改的更多详细信息,也许还请参见this

答案 1 :(得分:0)

如果查看open上的文档,您会发现使用w打开文件时,它将首先截断该文件的内容。意味着将没有您所描述的输出。

由于只想读取文件,因此应在open语句中使用r

f1 = open("reddy.txt", "r")