I am trying to rename a file, but python cannot find the file specified.
I have a file located here:
C:\Users\my_username\Desktop\selenium_downloads\close_of_day_reports\close-of-day-2022-04-24-2022-04-23.pdf
I am trying to rename the file to test.pdf
Here is the code I am using:
import os
os.rename(
src = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf",
dst = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf"
)
The error message I am getting is:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf' ->
'C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf'
What am I doing wrong?
Edit #1:
The original file was not deleted, it still exists.
It's really strange, when I run it the first time, the file does not get renamed, but when I run it again, it does.
Weird, for some reason it works in Python Shell, but not my Python file.
Edit #2:
I am using Selenium to download the file. When I comment the part of my code out that downloads the file from Selenium, my os.rename code works fine. Weird.
Based off the error, I think you are still leaving one the original name or not changing the right one.
import os
os.rename(
src = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\test.pdf",
dst = "C:\\Users\\my_username\\Desktop\\selenium_downloads\\close_of_day_reports\\close-of-day-2022-04-24-2022-04-23.pdf"
)
I'm pretty sure you ran the code once, renamed the file, and now it won't run again because you already renamed it.
Careful reading is your friend. Computers don't know or care what you meant:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\my_usernamer\Desktop\selenium_downloads\close_of_day_reports\close-of-day-2022-04-24-2022-04-23.pdf'
See the stray r in the path?
Found the solution:
When you download files using Selenium, you need to put in a sleep method for a few seconds and then you can download/move files without a problem.
Put this in your code after downloading the file, before downloading another:
from time import sleep
sleep(10)
pass
You may need to increase the sleep value, but 10 worked for me. The number inside of sleep represents seconds, so sleep(10) means to wait 10 seconds.
Related
I'm just trying to rename a file or move it to another directory. Either option will work for me. I have the most basic code here that I could find on the internet (first python project here by the way).
import shutil
import os
while True:
for file in os.listdir("C:/Users/lines/OneDrive/Desktop/loc1"):
if file.endswith(".txt"):
shutil.move("C:/Users/lines/OneDrive/Desktop/loc1/" + file, "C:/Users/lines/OneDrive/Desktop/loc2/moved.txt")
# os.rename("C:/Users/lines/OneDrive/Desktop/loc1/" + file, "C:/Users/lines/OneDrive/Desktop/loc2/moved.txt")
But no matter what I try, i ALWAYS get this error in my console when running the file:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:/Users/lines/OneDrive/Desktop/loc1/i000130126543220150615123030.txt' -> 'C:/Users/lines/OneDrive/Desktop/loc2/moved.txt'
I truly have no idea how to fix this. Can anyone help?
Edit: both directories are totally empty and only being used for this test purpose. No other text editors have these files open anywhere.
I am learning Python through 'Automate the Boring Stuff With Python' First Edition. In chapter 12, pg 267, we are supposed to open a file called example.xlsx.
The author's code reads:
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
type(wb)
However, when I try to open this file, I get the following error (this is the last line of the error):
FileNotFoundError: [Errno 2] No such file or directory: 'example.xlsx'
I know this file exists, because I downloaded it myself and am looking at it right now.
I have tried moving it to the current location in which Python 3.8 is, I have tried saving it with my Automate the Boring Stuff files that I've been working on the desktop, and I have tried saving it in every conceivable location on my machine, but I continue getting this same message.
I have imported openpyxl without error, but when I enter the line
wb = openpyxl.load_workbook('example.xlsx')
I have entered the entire pathway for the example.xlsx in the parenthesis, and I continue to get the same error.
What am I doing wrong? How am I supposed to open an Excel workbook?
I still don't understand how I am doing wrong, but this one is incredibly infuriating, and I feel incredibly stupid, because it must be something simple.
Any insight/help is greatly appreciated.
Your error is unambigous — your file in a supposed directory don't exist. Believe me.
For Python is irrelevant, whether you see it. Python itself must see it.
Specify the full path, using forward slashes, for example:
wb = openpyxl.load_workbook('C:/users/John/example.xlsx')
Or find out your real current (working) directory — and not the one supposed by you — with commands
import os
print(os.getcwd())
then move your example.xlsx to it, and then use only the name of your file
wb = openpyxl.load_workbook('example.xlsx')
You may also verify its existence with commands — use copy/paste from your code to avoid typos in the file name / path
import os.path
print(os.path.exists('example.xlsx')) # True, if Python sees it
or
import os.path
print(os.path.exists('C:/users/John/example.xlsx')) # True, if exists
to be sure that I'm right, i.e. that the error is not in the function openpyxl.load_workbook() itself, but in its parameter (the path to the file) provided by you.
I notice that the extension of the example file is not the same as described in the book, is example.csv. I was facing the same frustration as you
Long time reader, first time poster. I am very new to python and I will try to ask my question properly.
I have posted a snippet of the .py code I am using below. I am attempting to get the latest modified file in the current directory to be listed and then pass it along later in the code.
This is the error I get in my log file when I attempt to run the file:
WindowsError: [Error 2] The system cannot find the file specified: '05-30-2012_1500.wav'
So it appears that it is in fact pulling a file from the directory, but that's about it. And actually, the file that it pulls up is not the most recently modified file in that directory.
latest_page = max(os.listdir("/"), key=os.path.getmtime)
cause = channel.FilePlayer.play(latest_page)
os.listdir returns the names of files, not full paths to those files. Generally, when you use os.listdir(SOME_DIR), you then need os.path.join(SOME_DIR, fname) to get a path you can use to work with the file.
This might work for you:
files = [os.path.join("/", fname) for fname in os.listdir("/")]
latest = max(files, key=os.path.getmtime)
cause = channel.FilePlayer.play(latest)
I'm getting IOError: [Errno 13] Permission denied and I don't know what is wrong wit this code.
I'm trying to read a file given an absolute path (meaning only file.asm),
and a relative path (meaning /.../file.asm), and I want the program to write the file to whatever path is given - if it is absolute, it should write it to the current dir; otherwise, to the path given.
the code:
#call to main function
if __name__ == '__main__':
assem(sys.argv[1])
import sys
def assem(myFile):
from myParser import Parser
import code
from symbolTable import SymbolTable
table=SymbolTable()
# max size of each word
WORD_SIZE = 16
# rom address to save to
rom_addrs = 0
# variable address to save to
var_addrs = 16
# new addition
if (myFile[-4:] == ".asm"):
newFile = myFile[:4]+".hack"
output = open(newFile, 'w') <==== ERROR
the error given:
IOError: [Errno 13] Permission denied: '/Use.hack'
the way I execute the code :
python assembler.py Users/***/Desktop/University/Add.asm
What am I doing wrong here?
Just Close the opened file where you are going to write.
It looks like you're trying to replace the extension with the following code:
if (myFile[-4:] == ".asm"):
newFile = myFile[:4]+".hack"
However, you appear to have the array indexes mixed up. Try the following:
if (myFile[-4:] == ".asm"):
newFile = myFile[:-4]+".hack"
Note the use of -4 instead of just 4 in the second line of code. This explains why your program is trying to create /Use.hack, which is the first four characters of your file name (/Use), with .hack appended to it.
You don't have sufficient permissions to write to the root directory. See the leading slash on the filename?
This happened to me when I was using 'shutil.copyfile' instead of 'shutil.copy'. The permissions were messed up.
I had a same problem. In my case, the user did not have write permission to the destination directory. Following command helped in my case :
chmod 777 University
Maybe You are trying to open folder with open, check it once.
For me nothing from above worked. So I solved my problem with this workaround. Just check that you have added SYSTEM in directory folder. I hope it will help somoene.
import os
# create file
#staticmethod
def create_file(path):
if not os.path.exists(path):
os.system('echo # > {}'.format(path))
# append lines to the file
split_text = text_file.split('\n')
for st in split_text:
os.system('echo {} >> {}'.format(st,path))
Check if you are implementing the code inside a could drive like box, dropbox etc. If you copy the files you are trying to implement to a local folder on your machine you should be able to get rid of the error.
For me, this was a permissions issue.
Use the 'Take Ownership' application on that specific folder.
However, this sometimes seems to work only temporarily and is not a permanent solution.
FYI I had this permission error because the file that it was trying to create was already open/used by another program (was created last time the script was run, I had opened it with excel, and then got a permission error when it was trying to recreate it)
leaving this here in case someone else finds it useful, it is not the real solution to the question asked
I got this error because the directory didn't exist yet.
Solution: create the directory
import os
if not os.path.exists(directory):
os.makedirs(directory)
I have a rather simple program that writes HTML code ready for use.
It works fine, except that if one were to run the program from the Python command line, as is the default, the HTML file that is created is created where python.exe is, not where the program I wrote is. And that's a problem.
Do you know a way of getting the .write() function to write a file to a specific location on the disc (e.g. C:\Users\User\Desktop)?
Extra cool-points if you know how to open a file browser window.
The first problem is probably that you are not including the full path when you open the file for writing. For details on opening a web browser, read this fine manual.
import os
target_dir = r"C:\full\path\to\where\you\want\it"
fullname = os.path.join(target_dir,filename)
with open(fullname,"w") as f:
f.write("<html>....</html>")
import webbrowser
url = "file://"+fullname.replace("\\","/")
webbrowser.open(url,True,True)
BTW: the code is the same in python 2.6.
I'll admit I don't know Python 3, so I may be wrong, but in Python 2, you can just check the __file__ variable in your module to get the name of the file it was loaded from. Just create your file in that same directory (preferably using os.path.dirname and os.path.join to remain platform-independent).