问题
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