简体   繁体   English

如何使用Python中的csv模块将csv文件保存到绝对路径?

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

I currently have a program that collects data from .txt files in a folder and then saves that data to a csv file. 我目前有一个程序,该程序从文件夹中的.txt文件收集数据,然后将该数据保存到csv文件中。 Due to how I am planning on distributing this program, I need the Python file to live in the folder where these .txt files are located. 由于我计划分发该程序,因此我需要Python文件位于这些.txt文件所在的文件夹中。 However, I need the .csv files to be thrown to an absolute file path rather than being created in the same folder as the Python script and .txt documents. 但是,我需要将.csv文件扔到绝对文件路径,而不是在与Python脚本和.txt文档相同的文件夹中创建。 Here is what I have currently coded, 这是我目前编写的代码,

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)

I appreciate the help. 感谢您的帮助。

USing os.path.join() you can select your desire path for your file to be written. 使用os.path.join(),可以选择要写入文件的所需路径。 Here is an example: 这是一个例子:

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

Consider asking for the path from the script, and setting a default if not passed in. This would make your script a lot more flexible than having the path coded in it. 考虑从脚本询问路径,并设置一个默认值(如果未传入)。这将使脚本比在其中编码路径更加灵活。

You can use the click package which simplifies this a bit. 您可以使用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