从用户inpu创建复杂文件名

2024-04-19 23:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试改编当前包含以下片段的脚本:

#  Initialize the output files
working_dir = os.getcwd()
output_path = "{}/{}".format(working_dir, "output_Prelim")
if not os.path.exists(output_path):
    os.mkdir(output_path)
data_file = "{0}/RWA_2010_BUFFER_by_1.csv".format(output_path)
error_file = "{0}/failed_queries.txt".format(output_path)

在“数据文件”开头的声明中,文件名“RWA”和“2010”部分指进行特定调查的国家和年份。你知道吗

我正在尝试调整该段,以便文件名保留相同的通用格式,但允许用户输入不同的国家代码和年份。你知道吗

我可以使用以下代码生成一个名为“file\u name”的字符串:

print('Enter the country code')
cCode =input()
print('The country code is '+cCode)
print('Enter the survey year')
srvyYear =input()
print('The survey year is '+srvyYear)

file_name = r'"{0}/'+cCode+'_'+srvyYear+'_'+'BUFFER300_by_1.csv"'\

当我打印“文件名”时

"{0}/BDI_2009_BUFFER300_by_1.csv"

这看起来是对的,但我不知道该怎么处理它——特别是,如何将它理解为文件名而不是字符串。当我试图将该字符串与以“data\u file”开头的语句的其余部分连接起来时,我得到了一个语法错误。你知道吗

显然,我需要做一个教程,但不知道找什么。你知道吗

非常感谢,并为新手的问题道歉。你知道吗


Tags: csvthepath字符串formatoutputbyos
2条回答

不确定你的问题到底是什么,但是如果你想用其他东西替换{0}部分(例如data_file中的值),你可以做file_name.format(data_file)。你知道吗

为什么不对字符串使用join()方法,对paht使用os.path.join()?e、 g

file_name = os.path.join(out_path, '_'.join([cCode, srvyYear, 'BUFFER300_by_1.csv']))

你可以看到它的dochere,我相信这是你需要的,你最好不要自己连接字符串来构造路径或文件名。顺便说一句,os.path.join()可以构造不依赖于平台的文件名,这将是一个明智的选择(特别是对于Windows)。你知道吗

相关问题 更多 >