Rename file with a value stored in Variable in Python - python-3.x

I have a file and want to rename the file with and get the name from
cellObj.value
os.rename(r'C:\Users\Com\Downloads\Software 02E - Installed software on a specific computer.xlsx',r'C:\Users\Com\Downloads\OUTPUT.xlsx')
Need change Output by value in Cellobj (Example value: BPTPC0132)

Reading a cell value from a excel file is no problem - from your question I cant get which cell you want to read your filename from so I assume the first cell in your first sheet for now:
import xlrd
xl_workbook = xlrd.open_workbook("insertyourfilepathhere")
sheet_names = xl_workbook.sheet_names()
xl_sheet = xl_workbook.sheet_by_index(0)
cell = xl_sheet.cell(0,0)
output = cell.value
You can then use the output variable for saving your file.

This format worked for me
workbook.save(cellObj.value+".xlsx")

Related

Custom Filepath Exporting a Pandas Dataframe

I am working with financial data, and I am cleaning the data in Python before exporting it as a CSV. I want this file to be reused, so I want to make sure that the exported files are not overwritten. I am including this piece of code to help with this:
# Fill this out; this will help identify the dataset after it is exported
latestFY = '21'
earliestFY = '19'
I want the user to change the earliest and latest fiscal year variables to reflect the data they are working with, so when the data is exported, it is called financialData_FY19_FY21, for example. How can I do this using the to_csv function?
Here is what I currently have:
mergedDF.to_csv("merged_financial_data_FY.csv", index = False)
Here is what I want the file path to look like: financialData_FY19_FY21 where the 19 and 21 can be changed based on the input above.
You can use an f-string to update the strings that will be your file paths.
latestFY = '21'
earliestFY = '19'
filename = f"merged_financial_data_FY{earliestFY}_{latestFY}.csv"
mergedDF.to_csv(filename, index=False)
Link to docs

Reading excel files in python using dynamic dates in the file and sheet name

I have a situation in which I would want to read an excel file on a daily basis where the file name is written in the following format : file_name 08.20.2018 xyz.xlsx and gets updated daily where the date getting changed on a daily basis.
The same thing I need to do when this file is being read, I need to extract the data from a sheet whose naming convention also changes daily with the date. An example sheet name is sheet1-08.20.2020-data
How should I achieve this? I am using the following code but it does not work:
df = pd.read_Excel(r'file_name 08.20.2018 xyz.xlsx', sheet_name = 'sheet1-08.20.2020-data')
how do I update this line of code so that it picks the data dynamically daily with new dates coming in. And to be clear here, the date will also be incremental with no gaps.
You could use pathlib and the datetime module to automate the process :
from pathlib import Path
from datetime import date
#assuming you have a directory of files:
folder = Path(directory of files)
sheetname = f"sheet1-0{date.today().month}.{date.today().day}.{date.today().year}-data"
date_string = f"filename 0{date.today().month}.{date.today().day}.{date.today().year}.xlsx"
xlsx_file = folder.glob(date_string)
#read in data
df = pd.read_excel(io=next(xlsx_file), sheet_name = sheetname)

How to import multiple excel file into one excel file by using matlab?

I am a newbie in matlab and get stuck on this matter. I try to make one new file from multiple excel file by using matlab code. It managed to produce the new file. However the file is in a mess and I really do not have any idea how to do it. Here is the code:
% Merge multiple XLS files into one XLS file
[filenames, folder] = uigetfile('*.xls','Select the data file','MultiSelect','on'); % gets directory from any folder
% Create output file name in the same folder.
outputFileName = fullfile(folder, 'rainfall.xls');
fidOutput = fopen(outputFileName, 'wt'); % open output file to write
for k = 1 : length(filenames)
% Get this file name.
thisFileName = fullfile(folder, filenames{k});
% Open input file:
fidInput = fopen(thisFileName);
% Read text from it
thisText = fread(fidInput, '*char');
% Copy to output file:
fwrite(fidOutput, thisText);
fclose(fidInput); % close the input file
end
fclose(fidOutput);
I attah the picture showing how mess the resulted data is. Could you please help me? Thank you very much.
[files,folder] = uigetfile('*.xls','Select Files','MultiSelect','on');
output = fullfile(folder,'rainfall.xls');
c = cell(0,5);
for i = 1:numel(files)
c_curr = table2cell(readtable(fullfile(folder,files{i}),'ReadVariableNames',false));
c = [c; c_curr];
end
tab = cell2table(c,'VariableNames',{'MyVar1' 'MyVar2' 'MyVar3' 'MyVar4' 'MyVar5'});
writetable(tab,output);
Of course, every file must contain the same number of columns and every column must have the same underlying data type across all the files.
Use xlsread (or readtable, if you have a recent version of Matlab) instead of fread. Hope this helps.

Way to compare two excel files and CSV file

I need to compare two excel files and a csv file, then write some data from one excel file to another.
It looks like this:
CSV file with names which I will compare. For example (spam, eggs)
First Excel file with name and value of it. For example (spam, 100)
Second Excel file with name. For example (eggs)
Now, when I input file (second) into program I need to ensure that eggs == spam with csv file and then save value of 100 to the eggs.
For operating on excel files I'm using openpyxl and for csv I'm using csv.
Can I count on your help? Maybe there are better libraries to do that, because my trials proved to be a total failure.
Got it by myself. Some complex way, but it works like I wanted to. Will be glad for some tips to it.
import openpyxl
import numpy as np
lines = np.genfromtxt("csvtest.csv", delimiter=";", dtype=None)
compdict = dict()
for i in range(len(lines)):
compdict[lines[i][0]] = lines[i][1]
wb1 = openpyxl.load_workbook('inputtest.xlsx')
wb2 = openpyxl.load_workbook(filename='spistest.xlsx')
ws = wb1.get_sheet_by_name('Sheet1')
spis = wb2.get_sheet_by_name('Sheet1')
for row in ws.iter_rows(min_row=1, max_row=ws.max_row, min_col=1):
for cell in row:
if cell.value in compdict:
for wiersz in spis.iter_rows(min_row=1, max_row=spis.max_row, min_col=1):
for komorka in wiersz:
if komorka.value == compdict[cell.value]:
cena = spis.cell(row=komorka.row, column=2)
ws.cell(row=cell.row, column=2, value=cena.value)
wb1.save('inputtest.xlsx')
wb2.close()

Reading multiple Excel files, averaging, and writing to a single Excel file in Matlab

I am trying to expand some code I've written. It might be useful to include that script below:
% importing single excel sheet
data = xlsread('test_file.xlsx');
% averaging durations (exluding NaNs)
average_rx_time = mean(reaction_time, 'omitnan');
average_reach_dur = mean(reach_dur, 'omitnan');
average_lift_dur = mean(lift_dur, 'omitnan');
average_hold_dur = mean(hold_dur, 'omitnan');
average_withdrawal_dur = mean(withdrawal_dur, 'omitnan');
% Excel file output containing daily averages
a = [average_rx_time, average_reach_dur, average_lift_dur, average_hold_dur, average_withdrawal_dur];
data_cells = num2cell(a);
column_headers ={'Rx Time', 'Reach Dur', 'Lift Dur', 'Hold Dur', 'Withdrawal Dur'};
row_headers(1,1) ={'Day 1'};
output = [{' '} column_headers; row_headers data_cells];
xlswrite('Test.xls', output);
This portion works. It reads a bunch of values in a single Excel sheet, averages some numbers, then prints those averages to another Excel sheet. What I need to do now is read several files from a directory (they all exist in one folder and are the same file type), average the same values in each file, then print them with their respective file name in the spreadsheet.
I think I should use a loop, but I'm not sure where to implement it. I'm also not sure how to read multiple Excel files while printing to the same one. Any ideas?
Thanks,
Mickey
Use the cd and dir functions to get a list of files in a specified folder:
cd('\path\to\folder'); % set MATLAB's current folder
fileList = dir('*.xlsx'); % get list of .xlsx files in a struct array
for fileNum = 1:length(fileList)
fileName = fileList(fileNum).name;
% do whatever you want with fileName here
end

Resources