为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕森卡 2023-03-22 16:06:47
我有一个名为的文本文件,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 = ...这是我失败的部分代码,我不知道如何修复它。有没有人愿意帮助我?
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

从非结构化的 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"


查看完整回答
反对 回复 2023-03-22
  • 1 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信