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", "")
I have been given a Project on Python Programming so I wanted to ask you that how can I give relative directory paths to the generated files in Python so that it could be opened in other machines as absolute paths won't work on every PC
If you have write access to the folder containing your script then you can use something like
import sys, os
if __name__ == '__main__':
myself = sys.argv[0]
else:
myself = __file__
myself = os.path.abspath(myself)
whereami = os.path.dirname(myself)
print(myself)
print(whereami)
datadir = os.path.join(whereami, 'data')
if not os.path.exists(datadir):
os.mkdir(datadir)
datafile = os.path.join(datadir, 'foo.txt')
with open(datafile, 'w') as f:
f.write('Hello, World!\n')
with open(datafile) as f:
print(f.read())
In the file that has the script, you want to do something like this:
import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')
This will give you the absolute path to the file you're looking for, irrespective of the machine you are running your code on.
You can also refer these links for more information:
Link1
Link2
For more specific information, please make your question specific. i.e Please post the code that you have tried along with your inputs and expected outputs.
I am playing around with creating modules.I have two python scripts.The first (the module) has:
def abspath(relpath):
import os
absdir = os.path.realpath('__file__')
absdir = absdir.split('_')[0].replace('\\', '/')
filename = str(absdir + relpath )
print (filename)
return filename;
The second file (main) has:
import file_tools as ft
filename = ft.abspath('some/path/')
When I run Main, filename appears empty (Type:None). I have run the filename = abspath(etc) within the 'module', and it works. Clearly, I am missing something here!!
and doing this, so any help would be useful.
Thank's all.
MT
The problem lies in how you're finding the working directory; the preferred method being os.getcwd() (or os.getcwdb for Unix compatibility). Using that, we can see that your function boils down to:
def abspath(relpath):
return os.path.join(os.getcwd(), relpath)
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 ?
I want to change a.txt to b.kml.
Use os.rename:
import os
os.rename('a.txt', 'b.kml')
Usage:
os.rename('from.extension.whatever','to.another.extension')
File may be inside a directory, in that case specify the path:
import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)
As of Python 3.4 one can use the pathlib module to solve this.
If you happen to be on an older version, you can use the backported version found here
Let's assume you are not in the root path (just to add a bit of difficulty to it) you want to rename, and have to provide a full path, we can look at this:
some_path = 'a/b/c/the_file.extension'
So, you can take your path and create a Path object out of it:
from pathlib import Path
p = Path(some_path)
Just to provide some information around this object we have now, we can extract things out of it. For example, if for whatever reason we want to rename the file by modifying the filename from the_file to the_file_1, then we can get the filename part:
name_without_extension = p.stem
And still hold the extension in hand as well:
ext = p.suffix
We can perform our modification with a simple string manipulation:
Python 3.6 and greater make use of f-strings!
new_file_name = f"{name_without_extension}_1"
Otherwise:
new_file_name = "{}_{}".format(name_without_extension, 1)
And now we can perform our rename by calling the rename method on the path object we created and appending the ext to complete the proper rename structure we want:
p.rename(Path(p.parent, new_file_name + ext))
More shortly to showcase its simplicity:
Python 3.6+:
from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, f"{p.stem}_1_{p.suffix}"))
Versions less than Python 3.6 use the string format method instead:
from pathlib import Path
p = Path(some_path)
p.rename(Path(p.parent, "{}_{}_{}".format(p.stem, 1, p.suffix))
import shutil
shutil.move('a.txt', 'b.kml')
This will work to rename or move a file.
os.rename(old, new)
This is found in the Python docs: http://docs.python.org/library/os.html
As of Python version 3.3 and later, it is generally preferred to use os.replace instead of os.rename so FileExistsError is not raised if the destination file already exists.
assert os.path.isfile('old.txt')
assert os.path.isfile('new.txt')
os.rename('old.txt', 'new.txt')
# Raises FileExistsError
os.replace('old.txt', 'new.txt')
# Does not raise exception
assert not os.path.isfile('old.txt')
assert os.path.isfile('new.txt')
See the documentation.
Use os.rename. But you have to pass full path of both files to the function. If I have a file a.txt on my desktop so I will do and also I have to give full of renamed file too.
os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')
One important point to note here, we should check if any files exists with the new filename.
suppose if b.kml file exists then renaming other file with the same filename leads to deletion of existing b.kml.
import os
if not os.path.exists('b.kml'):
os.rename('a.txt','b.kml')
import os
# Set the path
path = 'a\\b\\c'
# save current working directory
saved_cwd = os.getcwd()
# change your cwd to the directory which contains files
os.chdir(path)
os.rename('a.txt', 'b.klm')
# moving back to the directory you were in
os.chdir(saved_cwd)
Using the Pathlib library's Path.rename instead of os.rename:
import pathlib
original_path = pathlib.Path('a.txt')
new_path = original_path.rename('b.kml')
Here is an example using pathlib only without touching os which changes the names of all files in a directory, based on a string replace operation without using also string concatenation:
from pathlib import Path
path = Path('/talend/studio/plugins/org.talend.designer.components.bigdata_7.3.1.20200214_1052\components/tMongoDB44Connection')
for p in path.glob("tMongoDBConnection*"):
new_name = p.name.replace("tMongoDBConnection", "tMongoDB44Connection")
new_name = p.parent/new_name
p.rename(new_name)
import shutil
import os
files = os.listdir("./pics/")
for key in range(0, len(files)):
print files[key]
shutil.move("./pics/" + files[key],"./pics/img" + str(key) + ".jpeg")
This should do it. python 3+
How to change the first letter of filename in a directory:
import os
path = "/"
for file in os.listdir(path):
os.rename(path + file, path + file.lower().capitalize())
then = os.listdir(path)
print(then)
If you are Using Windows and you want to rename your 1000s of files in a folder then:
You can use the below code. (Python3)
import os
path = os.chdir(input("Enter the path of the Your Image Folder : ")) #Here put the path of your folder where your images are stored
image_name = input("Enter your Image name : ") #Here, enter the name you want your images to have
i = 0
for file in os.listdir(path):
new_file_name = image_name+"_" + str(i) + ".jpg" #here you can change the extention of your renmamed file.
os.rename(file,new_file_name)
i = i + 1
input("Renamed all Images!!")
os.chdir(r"D:\Folder1\Folder2")
os.rename(src,dst)
#src and dst should be inside Folder2
import os
import re
from pathlib import Path
for f in os.listdir(training_data_dir2):
for file in os.listdir( training_data_dir2 + '/' + f):
oldfile= Path(training_data_dir2 + '/' + f + '/' + file)
newfile = Path(training_data_dir2 + '/' + f + '/' + file[49:])
p=oldfile
p.rename(newfile)
You can use os.system to invoke terminal to accomplish the task:
os.system('mv oldfile newfile')