[英]Extracting file directory from a .txt file?
我有一个名为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 = ...
这是我失败的部分代码,我不知道如何修复它。 有没有人愿意帮助我?
从非结构化的 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}")
Output:
CSV File Path: BIN+"/testing.csv"
CSV File Description: "testing"
要阅读有关 configparser 的更多信息,您可以参考此处。
有关 configparser 的简单教程,您可以参考这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.