如何在Python中获得与CSV文件名称相同的CSV文件名称

时间:2019-03-22 10:05:42

标签: python csv

我有几个sql查询文件。我试图一个一个地运行每个文件,并为每个sql查询生成csv文件。但是我想将CSV文件名作为sql文件名。 例- 而运行survey_cust.txt sql文件的时间将生成csv文件survey_cust.csv的时间。 sql文件-“ survey_cust.txt” 生成CSV文件-“ survey_cust.csv”

                path1 = "D:/Users/SPate233/Downloads/NS dashboard/sql_query/*.txt"
                files = glob.glob(path1)
                i = 1
                for name in files:
                    try:
                        with open(name) as f:
                            sql_query = f.read()
                            cur.execute(sql_query)
                            result = cur.fetchall()

                            with open("output_%s.csv" % i, 'w') as fp:
                                a = csv.writer(fp, delimiter=',')
                                a.writerow([i[0] for i in cur.description])
                                a.writerows(result)
                            i+=1

                    except:
                        print("error")

2 个答案:

答案 0 :(得分:0)

您可能想解析SQL文件路径以获取文件名,并将其用作csv文件名。

csv_name = os.path.split(name)[1].split('.')[0] + ".csv"
#os.path.split(name)[1] gets you the file name with the extension (txt?)
#split by the extension and get the name, then add csv extension
with open(csv_name, 'w') as fp:
...

你在问什么吗?

答案 1 :(得分:0)

使用os.path.basename

import os
filename = os.path.basename('/root/dir/sub/file.txt')
# > filename = 'file.txt'

然后只需替换扩展范围即可:

fname, fext = os.path.splitext(filename)
csvfile = '{0}.csv'.format(fname)

或者只是:

name = '/root/dir/sub/file.txt'
csvfile = '{0}.csv'.format(os.path.splitext(os.path.basename(name))[0])