首页 > 解决方案 > 文件打开/读取的Python未定义行为

问题描述

我正在尝试使用从文本文件中读取内容,Python3.7以下是我的代码,我在 RHEL 7 上运行该程序

我导出了所需的环境变量(即 Sourcepath),所有 3 个文件的内容都相同

[sathish@WEB Exercises]$ pwd
/tmp/Exercises
[sathish@WEB Exercises]$ ls -l develop/global/src
total 12
-rw-r--r-- 1 skailas wheel 124 Dec 29 06:51 a.txt_bak
-rw-r--r-- 1 skailas wheel 124 Dec 29 06:54 b.txt
-rw-r--r-- 1 skailas wheel 124 Dec 29 06:53 version.txt
import os
import sys

# Variable used to store file contents
file_contents = None

def readfromfile(filename):
        # Check whether the environment variable SourcePath exists
        # If not create one and assign a default value
    if not os.environ.get("Sourcepath", None):
        print("Environment variable Sourcepath does not exists")
        print("Create the environment variable and assign default value")
        os.environ["Sourcepath"] = "/tmp/Exercises"

    print("Sourcepath=", os.environ.get("Sourcepath"), os.getcwd())
    print(os.path.join(os.environ["Sourcepath"],"develop","global","src",filename))

    try:
        fh = open(os.path.join(os.environ["Sourcepath"],"develop","global","src",filename), "r")

        if ( os.stat(filename).st_size == 0):
            print("File is empty");
        else:
            # Read the contents from file and store it in a
            # global variable file_contents
            global file_contents
            print("Opened file", filename)
            file_contents = fh.read()
            print("File contents are", file_contents)
            fh.close()
            print("File closed")
    except FileNotFoundError:
        print("File not found for Reading ... Exiting", filename)
        sys.exit()
    except:
        print("Other Error ... Exiting")
        sys.exit()

readfromfile('b.txt')

错误输出

[skailas@WEB Exercises]$  python3.7 fex.py
Environment variable Sourcepath does not exists
Create the environment variable and assign default value
Sourcepath= /tmp/Exercises /tmp/Exercises
/tmp/Exercises/develop/global/src/b.txt
File not found for Reading ... `Exiting b.txt`

上面提到的程序读取 file 的文件内容a.txt_bak。但是,当我调用该函数时readfromfile('b.txt') or readfromfile('version.txt') ,它会说"FILE NOT FOUND ERROR"

我真的很困惑为什么'a.txt_bak'可以工作,为什么它会报告其他两个文件的错误?有时,即使文件存在于同一路径中,我的程序也不会读取内容

我在 fclose() 上做错了什么还是我错过了什么?请帮助我理解这个问题

标签: python

解决方案


推荐阅读