Hi I am checking to see if a excel file is modified, and if it is basically save it as something else and open it. So it works the first time around, but on the second time I modify the file, I am getting error: The system cannot find the file specified: 'C:\example.xlsx'
Sometimes it would also throw: Permission denied: 'C:\Todolist2.xlsx'
Please help. Newbie here. Thank You
import time, os.path, os, openpyxl
from openpyxl import Workbook
currentFD = os.stat("C:\\example.xlsx")
while True:
modDate = os.stat("C:\\example.xlsx")
if (modDate > currentFD):
print('yes it does')
wb=openpyxl.load_workbook("C:\\example.xlsx")
wb.save("C:\\Todolist2.xlsx")
os.startfile("C:\\Todolist2.xlsx")
currentFD = modDate
You seem to have two different problems here but they may be related.
Since you gave a traceback for the Permission Denied error on C:\Todolist2.xlsx, let's look at that one.
On Windows, many programs, when they open a file, put a lock on it. This is especially true for "applications" programs, like Excel and Notepad. If one program has a file locked, any another program that tries to open that file to overwrite it will get a permissions error.
And that's exactly what you're seeing: The first time through, your code overwrites Todolist2.xslx, then uses startfile to tell Excel (or some application that's registered for Excel files) to open it, which works. Then it tries to overwrite the same file, which Excel presumably still has locked and open, which fails.
Depending on what you're actually trying to do here, there are a few possible workarounds:
Copy Todolist2.xlsx to a temporary file, then start that temporary.
Create new files Todolist2.xlsx, Todolist2-1.xlsx, etc., and keep opening them.
Use either COM automation or a GUI scripting framework like autogui to make Excel open a copy of the file rather than opening the file itself.
Use either of the above to make Excel close the file before overwriting the file and launching it.
Launch a new Excel instance to open the file using subprocess.Popen, so you can kill it and launch a new one.
Rewrite your whole code to build the spreadsheet using Excel COM automation, rather than by building a file to pass to it.
Related
This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 6 months ago.
I have again problems with that famous Exception.
The problem is the following:
I have wanted to write a simple code for an easy exercise about files and excel libraries (openpyxl) that I have to be make for my python programming course. At first, I have to say that I usually make all my codes in iOS.
For this time, I have wanted to do this exercise in my old PC whose O.S. is Windows, so I have exported the file where I work in iOS in a pen drive and next, export that file in my Windows desktop.
I opened VSC and the first code's line is the problem because I try to load the excel file but the exception FileNotFoundError appears.
As simple as write:
import openpyxl
fw = openpyxl.load_workbook("Data_File_2.xlsx")
The file when I'm writing the code is in the follow route: C:\Users\xxxx\Desktop\pyWork
which is the same route where the file "Data_File_2" is in it.
Well, the problem continues because every time I want to write a new code for working with extern files, this Exception appears again, even with other 'py' files that I made where I worked with extern files and now I can't run because this Exception appears again and block the program. (I'm talking about old files made in previously days or weeks which works correctly with external files)
For example, now I'm trying to open a try file .txt from a new py.file, both of them located in the same directory:
with open("try_to_open.txt","r") as op_file:
rfile = op_file.read()
print(rfile)
#The exception FileNotFoundError appears again in the first line.
I know that I can use try/else blocks but I want to know why this Exception appears, what is the Error in this case and why it appears every time I want to work with external file one time that the Exception appears at first.
I think I have found a solution but I dont know if it's correct for similar situations like this. I was able to resolve by writing as follows:
import openpyxl
file_work = openpyxl.load_workbook("Pyworks\\Data_File_2.xlsx")
I have a simple problem that I hope will have a simple solution.
I am writing python(2.7) code using the xlwt package to write excel files. The program takes data and writes it out to a file that is being saved constantly. The problem is that whenever I have the file open to check the data and python tries to save the file the program crashes.
Is there any way to make python save the file when I have it open for reading?
My experience is that sashkello is correct, Excel locks the file. Even OpenOffice/LibreOffice do this. They lock the file on disk and create a temp version as a working copy. ANY program trying to access the open file will be denied by the OS. The reason for this is because many corporations treat Excel files as databases but the users have no understanding of the issues involved in concurrency and synchronisation.
I am on linux and I get this behaviour (at least when the file is on a SAMBA share). Look in the same directory as your file, if a file called .~lock.[filename]# exists then you will be unable to read your file from another program. I'm not sure what enforces this lock but I suspect it's an NTFS attribute. Note that even a simple cp or cat fails: cp: error reading ‘CATALOGUE.ods’: Input/output error
UPDATE: The actual locking mechanism appears to be 'oplocks`, a concept connected to Windows shares: http://oreilly.com/openbook/samba/book/ch05_05.html . If the share is managed by Samba the workaround is to disable locks on certain file types, eg:
veto oplock files = /*.xlsx/
If you aren't using a share or NTFS on linux then I guess you should be able to RW the file as long as your script has write permissions. By default only the user who created the file has write access.
WORKAROUND 2: The restriction only seems to apply if you have the file open in Excel/LO as writable, however LO at least allows you to open a file as read-only (Go to File -> Properties -> Security, set Read-Only, Save and re-open the file). I don't know if this will also make it RO for xlwt though.
Hah, funny I ran across your post. I actually just implemented this tonight.
The issue is that Excel files write, and that's it, not both. You cannot read/write off the same object. So if you have another method to save data please do. I'm in a position where I don't have an option.. and so might you.
You're going to need xlutils it's the bread and butter to this.
Here's some example code:
from xlutils.copy import copy
wb_filename = 'example.xls'
wb_object = xlrd.open_workbook(wb_filename)
# And then you can read this file to your hearts galore.
# Now when it comes to writing to this, you need to copy the object and work off that.
write_object = copy(wb_object)
# Write to it all you want and then save that object.
And that's it, now if you read the object, write to it, and read the original one again it won't be updated. You either need to recreate wb_object or you need to create some sort of table in memory that you can keep track of while working through it.
Trying to determine if a certain excel file is already open. I have a script that opens up a template excel file and writes data to the file and then saves it as a specific formatted name. Now if the person runs the script again and forgets to close out of the excel file I get errors that stop the program saying cant save the file as it is already open. Is there a way to check if, not only a program is open (excel) but a specific file? That way I can prompt the user to either close the file or save it as another filename.
If the processing time of the input is really small you do not need to detect this before processing the file. You can easily catch the error that you describe with "I get errors that stop the program saying cant save the file as it is already open" and provide a meaningful error message to the user.
i just installed python
i am trying to run this script:
import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
print row
i am running on windows.
do i have to type each line individually into python shell or can i save this code into a text file and then run it from the shell?
where does some.csv have to be in order to run it? in the same c:\python26 folder?
what is this code supposed to do?
Yes, you can create a file. The interactive shell is only for learning syntax, etc., and toying with ideas. It's not for writing programs.
a. Note that the script must have a .py extension, e.g., csvprint.py. To run it, you enter python csvprint.py. This will try to load csvprint.py from the current directory and run it.
The some.csv file has to be in the current working directory, which doesn't have to be (in fact, almost never should be) in the Python folder. Usually this will be you home directory, or some kind of working area that you setup, like C:\work. It's entirely up to you, though.
Without knowing the csv module that well myself, I'm guessing it reads CSV separated values from the file as tuples and prints each one out on the console.
One final note: The usual way to write such logic is to take the input from the command-line rather than hard-coding it. Like so:
import csv
reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
print row
And run it like so:
python csvprint.py some.csv
In this case you can put some.csv anywhere:
python csvprint.py C:\stuff\csvfiles\some.csv
When you have IDLE open, click File > New Window. (Or hit Ctrl + N)
This opens up a new window for you that's basically just a text editor with Python syntax highlighting. This is where you can write a program and save it. To execute it quickly, hit F5.
You can do both! To run the code from a text file (such as 'csvread.py', but the extension doesn't matter), type: python csvread.py at the command prompt. Make sure your PATH is set to include the Python installation directory.
"some.csv" needs to be in the current directory.
This code opens a Python file descriptor specifically designed to read CSVs. The reader file descriptor then prints out each row of the CSV in order. Check the documentation out for a more detailed example: http://docs.python.org/library/csv.html
Type the code into a *.py file, and then execute it.
I think the file should be in the same folder as your *.py script.
This opens a file stored in comma separated value format and prints the contents of each row.
All import does "Python code in one module gains access to the code in another module by the process of importing it. The import statement is the most common way of invoking the import machinery, but it is not the only way". The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. There is no “CSV standard”, so the format is operationally defined by the many applications which read and write it. The lack of a standard means that subtle differences often exist in the data produced and consumed by different applications. These differences can make it annoying to process CSV files from multiple sources. Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.
The CSV module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats. All your code is doing is looping through that file.
i'm having some trouble figuring out how to save unicode into a file in python. I have the following code, and if i run it in a script test.py, it should create a new file called priceinfo.txt, and write what's in price_info to the file. But i do not see the file, can anyone enlighten me on what could be the problem?
Thanks a lot!
price_info = u'it costs \u20ac 5'
f = codecs.open('priceinfo.txt','wb','utf-8')
f.write(price_info)
f.close()
I can think of several reasons:
the file gets created, but in a different directory. Be certain what the working
directory of the script is.
you don't have permission to create the file, in the directory where you want to create it.
you have some error in your Python script, and it does not get executed at all.
To find out which one it is, run the script in a command window, and check for any error output that you get.
Assuming no error messages from the program (which would be the result of forgetting to import the codecs module), are you sure you're looking in the right place? That code writes priceinfo.txt in the current working directory (IOW are you sure that you're looking inside the working directory?)