从 .txt 文件中提取文件目录?

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


inputCsvFile = BIN+"/testing.csv"

description = "testing"

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


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


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


f = open("testConfigFile","r")

line = f.readlines(f)

if line.startswith("inputCsvFile = ")

  inputfile = ...

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


慕森卡
浏览 105回答 1
1回答

天涯尽头无女友

从非结构化的 txt 文件中读取配置并不是最好的主意。Python 实际上能够解析以某种方式构造的配置文件。我已经重组了您的 txt 文件,以便更容易使用。配置文件扩展名并不重要,在本例中我将其更改为 .ini。应用程序.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"
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python