csv 文件未保存在 python 中的不同目录中

csv file isn't saved in different directory in python

我的代码从目录中读取一堆 json 文件并从这些文件中提取“频率”和“衰减”数据并写入 csv 文件。现在我想将该 csv 文件保存在不同的目录中。代码执行没有任何错误,但保存在当前目录中。谁能帮忙解决这个问题?

import csv
import glob
import json
import os

site = 'alpha'
frequency_to_check = '196050.000'
json_dir_name = 'V:/temp/test/'
json_pattern = os.path.join(json_dir_name, '*.json')
total_files = glob.glob(json_pattern)
atten = []
timestamp = []
save_path = 'V:/python/result/'
if not os.path.isdir(save_path):
    os.makedirs(save_path)
filename = f'{site}-{frequency_to_check}.csv'
with open(filename, 'w', newline='') as csv_file:
    for file in total_files:
        with open(file) as json_file:
            output_json = json.load(json_file)
            for key in output_json:
                if key['start-freq'] == frequency_to_check:
                    csv.writer(csv_file).writerow([key['start-freq'], key['attenuation']])
    save_file = os.path.join(save_path, filename)
    csv_file.close()

print(f'Total files processed {len(total_files)}')

据我推断问题在这里:

csv.writer(csv_file).writerow([key['start-freq'], key['attenuation']])

csv_file 是您加载到内存中的对象,每次执行此行时,您只是在已打开的文件中写入行。之后你只是创建一个新路径:

save_file = os.path.join(save_path, filename)

关闭文件时也从未真正使用过。

要解决此问题,我建议您将 save_path 作为 csv 文件:

import csv
import glob
import json
import os

site = 'alpha'
frequency_to_check = '196050.000'
json_dir_name = 'V:/temp/test/'
json_pattern = os.path.join(json_dir_name, '*.json')
total_files = glob.glob(json_pattern)
atten = []
timestamp = []
save_path = 'V:/python/result/'
if not os.path.isdir(save_path):
    os.makedirs(save_path)
filename = f'{site}-{frequency_to_check}.csv'
save_file = os.path.join(save_path, filename)
with open(save_file, 'w', newline='') as csv_file:
    for file in total_files:
        with open(file) as json_file:
            output_json = json.load(json_file)
            for key in output_json:
                if key['start-freq'] == frequency_to_check:
                    csv.writer(csv_file).writerow([key['start-freq'], key['attenuation']])
    
    csv_file.close()

print(f'Total files processed {len(total_files)}')

我想这应该可行。