簡體   English   中英

如何使用Python中的csv模塊將csv文件保存到絕對路徑?

[英]How do I save a csv file to an absolute path using the csv module in Python?

我目前有一個程序,該程序從文件夾中的.txt文件收集數據,然后將該數據保存到csv文件中。 由於我計划分發該程序,因此我需要Python文件位於這些.txt文件所在的文件夾中。 但是,我需要將.csv文件扔到絕對文件路徑,而不是在與Python腳本和.txt文檔相同的文件夾中創建。 這是我目前編寫的代碼,

def write_to_csv(journal_list):
    #writes a list of journal dictionaries to a csv file.
    import csv

    username = "Christian"  
    csv_name = username + ".csv" 

    myFile = open(csv_name, 'w')  
    with myFile:  
        myFields = ["filename", "username", "project_name", "file_path",
            "date", "start_time", "end_time", "length_of_revit_session",
            "os_version", "os_build", "revit_build", "revit_branch",
            "cpu_name", "cpu_clockspeed", "gpu_name", "ram_max", "ram_avg", "ram_peak",
            "sync_count", "sync_time_total", "sync_time_peak", "sync_time_avg",
            "commands_total", "commands_hotkey_percentage", "commands_unique",
            "commands_dynamo", "commands_escape_key", "commands_most_used"]
        writer = csv.DictWriter(myFile, fieldnames=myFields)    
        writer.writeheader()
        for item in journal_list:
            try:
                writer.writerow(item)
            except:
                print("error writing data to:", item)

感謝您的幫助。

使用os.path.join(),可以選擇要寫入文件的所需路徑。 這是一個例子:

import os
desier_path = '/home/foo/'
file_path = os.path.join(dest_dir, csv_name)
with open(file_path, 'w'):
...

考慮從腳本詢問路徑,並設置一個默認值(如果未傳入)。這將使腳本比在其中編碼路徑更加靈活。

您可以使用click程序包 ,以使其簡化。

import os
import click

def write_to_csv(path, journal_list):
    # .. your normal code
    file_path = os.path.join(path, '{}.csv'.format(username))
    # .. rest of your code here

@click.command()
@click.option('--output_dir', default='/home/foo/bar/', help='Default path to save files')
def main(output_dir):
   write_to_csv(output_dir)

if __name__ == '__main__':
   main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM