Open a file name +date as csv in Python [closed]

自闭症网瘾萝莉.ら 提交于 2020-01-07 06:24:36

问题


I want to be able to open a file name automatically and save it as a .csv, the files I produce are always called the same thing + todays date. For example todays spreadsheet could be called:

"TODAYS SHEET" + Todays date.xls

Stored in location

C:\A\B\C\D

How would I get the code to open todays .xls file and save it as a .csv in location

C:\A\B\C\D\E

I ultimately want to load data directly from this .csv file for comparison with a webscraper, so there may well be a method to open a .xls file as a .csv without saving it as a .csv in a second location.


回答1:


It should look like something close to that:

import datetime
today_string = datetime.datetime.today().strftime('%x')

with open('C:/A/B/C/D/TODAYS SHEET' + today_string + '.csv', 'w') as my_file:
    my_file.write('a,a,a,a,a,a')

You can have a look at the string format for the strftime function. Also have a look at the open function and what you can do with files




回答2:


To open the csv i would use xlrd.

import csv
import datetime
import os

import xlrd

path = "C:\Users\John\Desktop"
file_name = "TODAYS SHEET " + datetime.datetime.today().strftime('%Y-%m-%d') + ".csv"

with open(os.path.join(path, file_name), 'w') as file_:

    writer = csv.writer(file_)

    workbook = xlrd.open_workbook('herp.xlsx')
    worksheet = workbook.sheet_by_name('A Snazzy Title')

    num_rows = worksheet.nrows - 1
    curr_row = -1

    while curr_row < num_rows:
        curr_row += 1
        row = [cell.value for cell in worksheet.row(curr_row)]
        writer.writerow(row)


来源:https://stackoverflow.com/questions/17261969/open-a-file-name-date-as-csv-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!