python - 文件不包含节标题 - Python

标签 python sectionheader configuration-files

我正在尝试使用 SafeConfigParser 读取 python 3.7 中的配置文件。我尝试过给出完整的文件名(带文件位置)、仅给出文件名(不带文件位置)、使用 SafeConfigParser 中的 readfp 函数、仅使用 configparser 而不是 safeconfigparser,但它们都不起作用。我 100% 确定至少正在读取正确的文件。

这是我的Python代码:

from configparser import SafeConfigParser
import os

def main():
    filename = "C:/Users/Umer Sherdil Paracha/Desktop/distutils.cfg"
    if os.path.isfile(filename):
        parser = SafeConfigParser()
        parser.read(filename)
        print(parser.sections())
        screen_width = parser.getint('graphics','width')
        screen_height = parser.getint('graphics','height')
    else:
        print("Config file not found")

if __name__=="__main__":
    main()

这是我的 cfg 文件:

[GRAPHICS]
height = 600
width = 800

我完全被这个愚蠢的问题困扰了。在这方面的任何帮助将不胜感激。谢谢。

最佳答案

很难确定,但我猜你的文件名字符串有问题。

首先尝试这段调试代码:

filename = "C:/Users/Umer Sherdil Paracha/Desktop/distutils.cfg"
with open(filename) as file:
    print("Successfully got to this line!")

我猜这会引发文件未找到错误。造成这种情况的原因可能有几个(尽管您始终可以通过右键单击文件并打开属性来仔细检查路径是否正确):

  1. 您正在使用 Unix 风格的斜杠。 Windows typically uses backslashes ()
  2. 当你开始在字符串中使用反斜杠时,Python 可能会感到困惑,因为反斜杠也用于转义特殊字符。告诉 python 这是一个raw string在起始引号前添加 r:r"\I will not\escape the backslashes"

我相信你的文件名变量应该如下所示:

filename = r"C:\Users\Umer Sherdil Paracha\Desktop\distutils.cfg"

如果您在文件字符串中进行这两项更改,我怀疑上述测试代码将起作用,并且在进行这些更改后您的真实代码也将起作用。

成功打开文件后,请记住 python 始终区分大小写,因此您必须更新以下两行代码,以反射(reflect) .cfg 文件中使用的大小写:

screen_width = parser.getint('GRAPHICS','width')
screen_height = parser.getint('GRAPHICS','height')

关于python - 文件不包含节标题 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54163636/

相关文章:

python - 如何从 Django 中的 urls.py 访问 HttpRequest

安卓 : ListView get jumbled up while trying to write ViewHolder class for ListView with Section Headers

swift - UICollectionView 部分页眉和页脚显示错误的方式 - iOS

file - 是否有一种既定的方法可以将配置文件用于已部署的 MATLAB 应用程序?

python - 嵌套 python 理解中的 "Name * not defined"

python - 在 python 中的嵌套 json 字典中查找值

ios - 在不丢失部分标题的情况下更改 UITable 部分背景颜色

arrays - Bash 从配置文件中解析数组

python - 在 Python 中处理配置文件

python - 什么时候用类,什么时候用字典?