FileNotFoundError when using os.rename() in Python - python

I'm following this post to rename the file name, but I got error below, I've tried lots of potential solutions I can find here but none of solves my issue:
import os
import datetime
current_date = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
current_date
os.rename(r'C:\Users\...\xxxx.csv', r'C:\Users\...\xxxx_' + str(current_date) + '.csv'
The Error is:
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\...\\xxx.csv -> 'C:\\Users\\...\\xxx_2020-04-14 16:43:56.csv'
How can I solve it?

It doesn't Seem to like the format of current_date
import os
import datetime
current_date = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
old = 'C://path//somefile.csv'
new = 'C://path//somefile'+'new.csv' #str(current_date)+'.csv'
os.rename(old,new)
This worked for me (windows), You can't use certain characters in filenames, in this case it's the ":" thats causing problems, changing it to '-' should solve it.

maybe the file really doesnt exist in your path.. use os.walk to check if the file inside the folder, just like this:
for _ in os.walk(path):
print(_)

Related

Renaming log files with Python using wildcard and datetime

I was searching today for options to manipulate some log files, after executing actions on them, and I found that Python has the os.rename resource, after importing the os module, but I have some regex doubts..
Tried to fit a wildcard "*****" on my file names, but Python seems not to understand it.
My file names are:
Application_2021-08-06_hostname_[PID].log
Currently I'm asking Python to read these application files, and search for defined words/phrases such as "User has logged in", "User disconnected" and etc. And he does well. I'm using datetime module so Python will always read the current files only.
But what I'm trying to do now, is to change the name of the file, after Python read it and execute something. So when he find "Today's sessions are done", he will change the name of the file to:
Application_06-08-2021_hostname_[PID].log
Because it will be easier for manipulating later..
Considering that [PID] will always change, this is the part that I wanted to set the wildcard, because it can be 56, 142, 3356, 74567 or anything.
Using the os.rename module, I've got some errors. What do you suggest?
Code:
import os
import time
from datetime import datetime
path = '/users/application/logs'
file_name = 'Application_%s_hostname_'% datetime.now().strftime('%Y-%m-%d')
new_file_name = 'Application_%s_hostname_'% datetime.now().strftime('%d-%m-%Y')
os.rename(file_name, new_file_name)
The error is:
OSError: [Errno 2] No such file or directory
You can use glob which allows for wildcards:
import glob, os
from datetime import datetime
current_date = datetime.now()
path = '/users/application/logs'
# note the use of * as wild card
filename ='Application_%s_hostname_*'% current_date.strftime('%Y-%m-%d')
full_path = os.path.join(path, filename)
replace_file = glob.glob(full_path)[0] # will return a list so take first element
# or loop to get all files
new_name = replace_file.replace( current_date.strftime('%Y-%m-%d'), current_date.strftime('%d-%m-%Y') )
os.rename(replace_file, new_name)

Remove certain strings from filenames inside a folder

I have a folder that contains a bunch of text files.
32167.pdf.txt
20988.pdf.txt
45678.pdf.txt
:
:
99999.pdf.txt
I would like to remove ".pdf" from all the filenames inside that folder (As showed below).
32167.txt
20988.txt
45678.txt
:
:
99999.txt
I tried to use os to do it but throwing me an error FileNotFoundError: [Errno 2] No such file or directory: '.txt' -> '.txt'
Here is my code:
for filename in os.listdir('/Users/CodingStark/folder/'):
os.rename(filename, filename.replace('.pdf', ''))
I am wondering are there any other ways to achieve this instead of using os? Or os is the fastest way to do it? Thank you!!
I think I know what's wrong. filename will contain just the file's name, not a complete path. Try this:
dir = '/Users/CodingStark/folder/'
for filename in os.listdir(dir):
os.rename(dir + filename, dir + filename.replace('.pdf', ''))
You should really use pathlib when working with paths. It has alternatives for most of the os functions and it just makes more sense to use and is definitely more portable.
To the task in hand:
from pathlib import Path
root = Path('/Users/CodingStark/folder/')
for path in root.glob("*.pdf.txt"):
path.rename(path.with_name(path.name.replace(".pdf", "")))
# or:
# path.with_suffix('').with_suffix(".txt")
# or:
# str(path).replace(".pdf", "")

Write a Python directory path string that contains both single and double back slash?

I know python prints strings containing backslash differently from the way it actually is. I do not care about print statements but I just want the string to begin with two back slashes and all the other slashes to be one slash like this:
\\xyz\abc\fish\orange
Currently, this is what I have coded and I get the error below:
import shutil
dir_path = r"\\xyz\abc\fish\orange"
print(dir_path)
shutil.copyfile("U:/Profile/Downloads/document1", dir_path)
I get an error:
FileNotFoundError: [Errno 2] No such file or directory: '\\\\xyz\\abc\\fish\\orange'
I replaced the actual directory name with mock names but what's important is formatting the slashes. I would prefer to fix this issue while not using os library. Thank you.
You can do like this.
import shutil
from pathlib import Path
dir_path = Path(r"\xyz\abc\fish\orange\document1") print(dir_path)
if dir_path.exist():
shutil.copyfile("U:/Profile/Downloads/document1", dir_path)
else:
print(f"{dir_path} do not exist")
You can also catch the error.
import shutil
dir_path = r"\xyz\abc\fish\orange\document1" print(dir_path)
try:
shutil.copyfile("U:/Profile/Downloads/document1", dir_path)
except FileNotFoundError:
print(f"{dir_path} do not exist")

How to copy an image with date in the new filename?

I'm looking for a way to copy an image file from a given source with Python.
I did read several stuff on the internet but what I found was always working just on one specific platform. I would like to know if there exists a functionality in Python that would make it possible to easily copy an image file ?
My target would be to have this in the end :
folder/image_title.jpg
copying the image
new_folder/new_image_title.jpg
with the *new_image_title* being the date of the day.
My code looks like this at the moment :
import shutil
import datetime
shutil.copy('folder/alpha.jpg', 'new_folder/'datetime.date()'.jpg')
But I get an error: SyntaxError: invalid syntax
Update:
You probably want a simple string for your second argument:
instead of this:
shutil.copy('folder/alpha.jpg', 'new_folder/'datetime.date()'.jpg')
try:
dest = new_folder + '/' + str(datetime.date(2012, 8, 19)) + '.jpg'
shutil.copy('folder/alpha.jpg', dest)
with:
new_folder = 'bla'
dest becomes:
'bla/2012-08-19.jpg'
tweak as needed to make the name unique (add time stamp?). Also note, it's usually better to use os.path.join() for creating new paths.
You are getting a SyntaxError because your string forming syntax is incorrect. Corrected, the code would look like this:
import shutil
import datetime
import os
DATE_FORMAT = '%Y-%m-%d'
filename = 'folder/alpha.jpg'
target_folder = 'new_folder'
ext = os.path.splitext(filename)[1]
shutil.copy(filename,
os.path.join(target_folder, '%s%s'
% (datetime.datetime.now().strftime(DATE_FORMAT), ext))
install exiftool
and run command in the photo path:
exiftool -d "./%Y-%m-%d" "-directory
I'm done with it, thanks to you :)
So here is my final version, in case it could help other people :
import shutil
import datetime
now = datetime.datetime.now()
date=str(now.year)+'-'+str(now.month)+'-'+str(now.day)
new_folder = "source/new_folder"
dest = new_folder + '/' + str(date) + '.jpg'
shutil.copy('source/alpha.jpg', dest)
One last thing : at the moment, the program just runs without saying anything. So does anyone knows how to print a message saying whether or not the copying did work ?

Python IOError exception when creating a long file

I get an IOError shown below when trying to open a new file using "open (fname, 'w+')". The complete error message is below.
The file does not exist, but I verified using "os.access(dir_name, os.W_OK)" and "os.path.exists (dir_name)" that the parent directory for the file does exist.
I am wondering if the file name is just too long for Windows, or if I am doing something wrong. Any tips would be appreciated. Thank you very much.
Error message:
IOError: [Errno 2] No such file or directory: 'C:\Documents and
Settings\Administrator\op_models\Corp_Network_Nov12\abcde_corporate_nov_12.project\abcde_corporate_nov_12-ctr.rptd.dir\ctr\Non
Business Hours for
Weeknights\hourly_data_for_2_weeks\1294897740\json.data\Link\0\Link
Utilization\analyzer393146160-data0.js'
In the Windows API the maximum path length is limited to 260 characters.
http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx
Update: prepend "\\?\" to the path.
Here is some related code which works for me (I have very long file names and paths):
for d in os.walk(os.getcwd()):
dirname = d[0]
files = d[2]
for f in files:
long_fname = u"\\\\?\\" + os.getcwd() + u"\\" + dirname + u"\\" + f
if op.isdir(long_fname):
continue
fin = open(long_fname, 'rb')
...
Note that for me it only worked with a combination of all of the following:
Prepend '\\?\' at the front.
Use full path, not relative path.
Use only backslashes.
In Python, the filename string must be a unicode string, for example u"abc", not "abc".
Also note, for some reason os.walk(..) returned some of the directories as files, so above I check for that.
You can monkey patch the tarfile module with this:
import tarfile
def monkey_patch_tarfile():
import os
import sys
if sys.platform not in ['cygwin', 'win32']:
return
def long_open(name, *args, **kwargs):
# http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx#maxpath
if len(name) >= 200:
if not os.path.isabs(name):
name = os.path.join(os.getcwd(), name)
name = "\\\\?\\" + os.path.normpath(name)
return long_open.bltn_open(name, *args, **kwargs)
long_open.bltn_open = tarfile.bltn_open
tarfile.bltn_open = long_open
monkey_patch_tarfile()
If it's not the length of the filename, it's the contents of the filename...
Python is treating '\12' as a control sequence.
>>> fn='C:\Documents and Settings\Administrator\op_models\Corp_Network_Nov12\abcde_corporate_nov_12.project\abcde_corporate_nov_12-ctr.rptd.dir\ctr\Non Business Hours for Weeknights\hourly_data_for_2_weeks\1294897740\json.data\Link\0\Link Utilization\analyzer393146160-data0.js'
>>> print fn
C:\Documents and Settings\Administrator\op_models\Corp_Network_Nov12bcde_corporate_nov_12.projectbcde_corporate_nov_12-ctr.rptd.dir\ctr\Non Business Hours for Weeknights\hourly_data_for_2_weeks
94897740\json.data\Link\Link Utilizationnalyzer393146160-data0.js
Using raw strings for Windows filenames will help:
>>> fn=r'C:\Documents and Settings\Administrator\op_models\Corp_Network_Nov12\abcde_corporate_nov_12.project\abcde_corporate_nov_12-ctr.rptd.dir\ctr\Non Business Hours for Weeknights\hourly_data_for_2_weeks\1294897740\json.data\Link\0\Link Utilization\analyzer393146160-data0.js'
>>> print fn
C:\Documents and Settings\Administrator\op_models\Corp_Network_Nov12\abcde_corporate_nov_12.project\abcde_corporate_nov_12-ctr.rptd.dir\ctr\Non Business Hours for Weeknights\hourly_data_for_2_weeks\1294897740\json.data\Link\0\Link Utilization\analyzer393146160-data0.js
Update
Alternatively, use forward slashes '/' instead of backslashes '\', since these will work on all operating systems and will save you hassles with backslashes right at the end of a pathname as in your comments.
See also os.path.join() .
Update 2
Simplified demonstration of problem:
>>> open('.\12\n\r\file.txt')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '.\n\n\r\x0cile.txt'
>>> open('./12/n/r/file.txt')
<open file './12/n/r/file.txt', mode 'r' at 0x7ff83f98>
C:\Users\johnysweb>copy .\12\n\r\file.txt con
Blah
1 file(s) copied.
Check the length of the entire path and then append the necessary Windows long path format. It should be noted that this doesn't work for accessing data from remote directories i.e. paths that begin with '\\some_remote_location\..' so you will need to map that directory locally in order to get "long path" to work.
if len(path_and_file) > 250: #I think the max is 260 but I left a buffer :)
path_and_file = '\\\\?\\'+path_and_file

Categories

Resources