How does python access the file from a right click on Windows - python

I've written a simple python script that takes a .csv file, rearranges it and spits out an excel file. My aim is to be able to right click on a .csv file in Windows and for it to generate an .xslx file. I've used PyInstaller to successfully create an .exe and I've used default programs editor to put my executable in the context menu when csv files are right clicked. What I can't figure out is how to do the I/O correctly.
What I have is :
import fileinput
import csv
try:
csv_filename = fileinput.filename()
print(csv_filename)
except: print('no input')
with open(filename_csv, 'rt', newline='', encoding='utf8') as csvfile:
# do stuff
# write xslx_filename
Which doesn't work.
How do I access the file windows passes me when I open a file?
Edit:
Just to clear up confusion. If I hard code the location of a csv file, my script works just fine. My problem is how do I access the file that Windows (presumably) passes to my script when I right click on a csv file and choose to open with csv2xslx (my script).

Thanks to martineau above for the pointer. The following made it work:
file = sys.argv[1]
with open(file, 'rt', newline='', encoding='utf8') as csvfile:
# do stuff
# write xslx_filename
I'm still not sure if that is the 'correct' way of doing it, but it works so I'm happy.

Related

How to run another Python script in a different folder, which takes a csv file in its own path to read?

I have a mainprogram called: onescripttorulethemall.py(Let us call this onescript.py)
I have a different folder(call it 'SCRIPTSTOBERULED'), located in a different path than my mainprogram. In this folder, there is also an other folder(lets call it folder_1) and this folder contains one python script(csvwriter_1.py) and one csv file. What this python script(csvwriter_1.py) do is basicaly, it reads the csv file and write it into an other csv file after creating it.
This is the code that I have in my mainprogram(onescript.py):
user='hkaan'
python_projects_folder='PycharmProjects'
scripts_to_be_ruled_folder='SCRIPTSTOBERULED'
path=f'C:\\Users\\{user}\\{python_projects_folder}\\{scripts_to_be_ruled_folder}'
star=os.listdir(path)
#THIS PRINTS THE FIRST ELEMENT IN 'SCRIPTSTOBERULED' FOLDER, WHICH IS FOLDER_1
print(str(star[0]))
#THIS IS THE PATH TO FOLDER_1
path2=f'C:\\Users\\{user}\\{python_projects_folder}\\{scripts_to_be_ruled_folder}\\{str(star[0])}'
python_script=os.listdir(path2)
#THIS IS THE PATH TO CSVWRITER_1.
python_path=f'C:\\Users\\{user}\\{python_projects_folder}\\{scripts_to_be_ruled_folder}\\{str(star[0])}\\{python_script[0]}'
#THIS RUNS THE CSVWRITER_1.PY
exec(open(python_path).read())
#I TRIED THE OS.SYSTEM CODE BELOW TOO, BUT IT DID NOT WORK.
#os.system(python_path)
And this is the code I have in my csvwriter_1.py:
deneme='wololo.csv'
resto_hrefs=[]
with open(deneme, 'r', encoding='UTF-8') as rd:
reader = csv.reader(rd)
for lines in reader:
resto_hrefs.append(lines[0])
file_name='file.csv'
text=['kkkkkkkkk']
resto_hrefs.append(text)
with open(file_name, 'w', encoding='UTF-8', newline="") as csv_file:
wr = csv.writer(csv_file)
wr.writerows(resto_hrefs)
Please do not mind the un-meaningful words and the method. If I run csvwriter1.py, it gives me an output(in other words, successfully finishes running) because wololo.csv in its path. However, when I run my mainprogram(onescript.py), it gives me the error "No such file or directory: 'wololo.csv'". This error is surely expected, I want to learn how to overcome this issue.
Edit: The end goal I want to achive is, I want to run multiple scripts(like csvwriter_1) in different folders by running only my mainprogram. So the csv file and python scripts name will be different but similar in each folder. Thus, I want to write an efficient script in my mainprogram, not just copy/paste file and script names and run them.

Can't open csv file in "excel format"

I have the following code to create a CSV file.
with open('CSV\globalLS', 'a', newline = "") as f:
writer = csv.writer(f,quoting=csv.QUOTE_ALL )
writer.writerow([name, datetime.datetime.now().date(), openPrice, highPrice, lowPrice, closePrice])
However, once the file is created and I try to open it - using computer - the file type is listed as bigdEal and the file opening default setting - excel - is not shown.
It opens fine using notebook but it needs to be in an excel file.
Does anyone know what is happening?
Thanks
Specify the extension in the filename you are writing to:
with open('CSV\globalLS.csv', 'a', newline = "") as f:
This way, when you try and open the file, your operating system will be able to apply the default application used for .csv type.
If your default application is not set correctly for csv files, you need to set this yourself. The process will be dependent on your operating system.

python 3.4.3 unable to write to a file in a desktop folder

I have a simple code to write a file in a specific folder. System creates the file in the folder but couldn't write on it. It is on windows and I checked the IDE write access (Pycharm) they seems fine. File is empty.
Following with code is to read whether I could write or ensure the previous one is finished. It is not writing the short string to the file. I have tried it on command line but it didn't work there also.
with open ('C:/Users/***/Desktop/***/output.log',mode ='w', encoding ='utf-8') as a_file:
a_file.write ="test"
with open ('C:/Users/***/Desktop/***/output.log', encoding ='utf-8') as a_file:
print(a_file.read())
The write is a method (function), you need to call, instead of assigning to it.
with open ('C:/Users/***/Desktop/***/output.log', mode='w', encoding='utf-8') as a_file:
a_file.write("test") # <---

Python won't write each time new lines into text file

I have two python files, both of them in the same folder. The main file executes the whole function, making my program what I want it to do. The other file writes data to a text file.
However, there's one issue with writing data to the text file: instead of writing each time new lines to the existing text, it completely overwrites the whole file.
File responsible for writing data(writefile.py)
import codecs
def start(text):
codecs.open('D:\\Program Files (x86)\\Python342\\passguess.txt', 'a', 'utf-8')
with open('D:\\Program Files (x86)\\Python342\\passguess.txt', 'w') as file:
file.write(text + '\n')
I've tried out couple of things such as .join(text) or running the code from writefile.py in the main file. Nothing seems to work..
The problem lies with the line
with open('D:\\Program Files (x86)\\Python342\\passguess.txt', 'w') as file:
this one opens the file in write mode, to append you want 'a' option so just change to
with open('D:\\Program Files (x86)\\Python342\\passguess.txt', 'a') as file:
and you should be fine

Excel fails to open Python-generated CSV files

I have many Python scripts that output CSV files. It is occasionally convenient to open these files in Excel. After installing OS X Mavericks, Excel no longer opens these files properly: Excel doesn't parse the files and it duplicates the rows of the file until it runs out of memory. Specifically, when Excel attempts to open the file, a prompt appears that reads: "File not loaded completely."
Example of code I'm using to generate the CSV files:
import csv
with open('csv_test.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow([1,2,3])
writer.writerow([4,5,6])
Even the simple file generated by the above code fails to load in Excel. However, if I open the CSV file in a text editor and copy/paste the text into Excel, parse it with text to columns, and then save as CSV from Excel, then I can reopen the CSV file in Excel without issue. Do I need to pass an additional parameter in my scripts to make Excel parse the CSV files the same way it used to? Or is there some setting I can change in OS X Mavericks or Excel? Thanks.
Maybe I had the similar problem, the error message "SYLK: File format is not valid" when open python autogenerated csv file. The solution is really funny. The first two characters must not be I and D in uppercase (ID). Also see "SYLK: File format is not valid" error message when you open file.
Possible solution1: use *.txt instead of *.csv. In this case Excel (at least, 2010) will show you an import data wizard where you can specify delimiters, character encoding, field types, etc.
UPD: Solution2:
The python "csv" module has a "dialect" feature. For example, the following modification of your code generates valid csv file for my environment (Python 2.7, Excel 2010, Windows7, locale with ";" list delimiters):
import csv
with open('csv_test2.csv', 'wb') as f:
csv.excel.delimiter=';'
writer = csv.writer(f, dialect=csv.excel)
writer.writerow([1,2,3])
writer.writerow([4,5,6])

Categories