如何使用Python中的csv模块将csv文件保存到绝对路径?
我目前有一个程序,从文件夹中的.txt文件收集数据,然后将数据保存到csv文件中。由于我计划如何分发这个程序,我需要Python文件位于这些.txt文件所在的文件夹中。但是,我需要将.csv文件抛出到绝对文件路径,而不是创建在与Python脚本和.txt文档相同的文件夹中。这是我目前编写的代码如何使用Python中的csv模块将csv文件保存到绝对路径?,python,excel,csv,module,path,Python,Excel,Csv,Module,Path,我目前有一个程序,从文件夹中的.txt文件收集数据,然后将数据保存到csv文件中。由于我计划如何分发这个程序,我需要Python文件位于这些.txt文件所在的文件夹中。但是,我需要将.csv文件抛出到绝对文件路径,而不是创建在与Python脚本和.txt文档相同的文件夹中。这是我目前编写的代码 def write_to_csv(journal_list): #writes a list of journal dictionaries to a csv file. import c
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'):
...
使用os.path.join()可以为要写入的文件选择所需的路径。以下是一个例子:
import os
desier_path = '/home/foo/'
file_path = os.path.join(dest_dir, csv_name)
with open(file_path, 'w'):
...
考虑从脚本中请求路径,如果未传入,则设置默认值。这将使脚本比在其中编码路径更灵活 您可以使用简化了这一点的
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()
考虑从脚本中请求路径,如果未传入,则设置默认值。这将使脚本比在其中编码路径更灵活 您可以使用简化了这一点的
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()
你在哪里定义我的文件?
csv_name='/some/absolute/path/%s.csv'%username
@JohnGordon谢谢你,你是个天才!你能加上这个作为答案吗,这样我就可以把这个标记为已解决?谢谢ton@chrisz很抱歉,我修改了我原来的定义,只是为了问这个问题。我将重新添加那个变量,我忘了更改它。你在哪里定义myFile
?csv\u name='/some/absolute/path/%s.csv'%username
@JohnGordon谢谢你,你是个天才!你能加上这个作为答案吗,这样我就可以把这个标记为已解决?谢谢ton@chrisz很抱歉,我修改了我原来的定义,只是为了问这个问题。我将重新添加该变量,我忘了更改它。