【问题标题】:Extracting file directory from a .txt file?从 .txt 文件中提取文件目录?
【发布时间】:2020-07-22 03:29:44
【问题描述】:

我有一个名为testConfigFile 的文本文件,如下所示:

inputCsvFile = BIN+"/testing.csv"
description = "testing"

其中BIN 是我的文件夹的父目录(已在我的python 脚本中使用os.getcwd 声明)。

我现在面临的问题是,如何从testConfigFile.txt 中读取和提取BIN+"testing.csv"

由于名称testing.csv 可能会更改为其他名称,因此它将是一个变量。我打算这样做,首先脚本读取关键字"inputCsvFile = ",然后它会自动提取它后面的单词,即"BIN+"testing.csv"

f = open("testConfigFile","r")
line = f.readlines(f)
if line.startswith("inputCsvFile = ")
  inputfile = ...

这是我失败的部分代码,我不知道如何修复它。有人愿意帮助我吗?

【问题讨论】:

  • line 将是一个列表,你不能在上面使用startswith

标签: python csv file


【解决方案1】:

从非结构化的 txt 文件中读取配置并不是最好的主意。 Python 实际上能够解析以某种方式构造的配置文件。我已经重组了您的 txt 文件,使其更易于使用。配置文件扩展名无关紧要,在这种情况下我已将其更改为 .ini。

app.ini:

[csvfilepath]
inputCsvFile = BIN+"/testing.csv"
description = "testing"

代码:

from configparser import ConfigParser  # Available by default, no install needed.

config = ConfigParser()  # Create a ConfigParser instance.
config.read('app.ini')  # You can input the full path to the config file.

file_path = config.get('csvfilepath', 'inputCsvFile')
file_description = config.get('csvfilepath', 'description')

print(f"CSV File Path: {file_path}\nCSV File Description: {file_description}")

输出:

CSV File Path: BIN+"/testing.csv"
CSV File Description: "testing"

要了解更多关于 configparser 的信息,您可以参考here

关于configparser的简单教程,可以参考here

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    相关资源
    最近更新 更多