python - 文件打开/读取的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() 上做错了什么还是我错过了什么?请帮助我理解这个问题
解决方案
推荐阅读
- java - 为什么 Apache NiFi MergeRecords 处理器没有根据配置合并记录数?
- apache - 如何设置特定的 RewriteRule?
- ms-access - MS Access - 是否有一种简单的方法可以复制表单及其子表单的字段信息?
- mysql - 如何每天自动执行 mysql 查询,同时在查询中使用日期作为条件?
- python - Pandas 在列上加入 DataFrame 和 Series
- android - Android房间数据库关系问题
- python - 无法初始化语言服务器协议
- javascript - 在客户端检查时间执行
- sql - 如何设计表格以支持与默认值有很多关系?
- ios - 如何限制文本字段只能输入十进制数字?