Change filename prefix in Path PosixPath object - python

I need to change a prefix for a current file.
An example would look as follows:
from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')
# Current file with destination
print(file)
# Prefix to be used
file_prexif = 'A'
# Hardcoding wanted results.
Path('/Users/my_name/PYTHON/Playing_Around/A_testing_lm.py')
As can be seen hardcoding it is easy. However is there a way to automate this step?
There is a pseudo - idea of what I want to do:
str(file).split('/')[-1] = str(file_prexif) + str('_') + str(file).split('/')[-1]
I only want to change last element of PosixPath file. However it is not possible to change only last element of string

file.stem accesses the base name of the file without extension.
file.with_stem() (added in Python 3.9) returns an updated Path with a new stem:
from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')
print(file.with_stem(f'A_{file.stem}'))
\Users\my_name\PYTHON\Playing_Around\A_testing_lm.py

Use file.parent to get the parent of the path and file.name to get the final path component, excluding the drive and root.
from pathlib import Path
file = Path('/Users/my_name/PYTHON/Playing_Around/testing_lm.py')
file_prexif_lst = ['A','B','C']
for prefix in file_prexif_lst:
p = file.parent.joinpath(f'{prefix}_{file.name}')
print(p)
/Users/my_name/PYTHON/Playing_Around/A_testing_lm.py
/Users/my_name/PYTHON/Playing_Around/B_testing_lm.py
/Users/my_name/PYTHON/Playing_Around/C_testing_lm.py

Related

Raster to ASCII Conversion [duplicate]

Suppose from index.py with CGI, I have post file foo.fasta to display file. I want to change foo.fasta's file extension to be foo.aln in display file. How can I do it?
An elegant way using pathlib.Path:
from pathlib import Path
p = Path('mysequence.fasta')
p.rename(p.with_suffix('.aln'))
os.path.splitext(), os.rename()
for example:
# renamee is the file getting renamed, pre is the part of file name before extension and ext is current extension
pre, ext = os.path.splitext(renamee)
os.rename(renamee, pre + new_extension)
import os
thisFile = "mysequence.fasta"
base = os.path.splitext(thisFile)[0]
os.rename(thisFile, base + ".aln")
Where thisFile = the absolute path of the file you are changing
Starting from Python 3.4 there's pathlib built-in library. So the code could be something like:
from pathlib import Path
filename = "mysequence.fasta"
new_filename = Path(filename).stem + ".aln"
https://docs.python.org/3.4/library/pathlib.html#pathlib.PurePath.stem
I love pathlib :)
Use this:
os.path.splitext("name.fasta")[0]+".aln"
And here is how the above works:
The splitext method separates the name from the extension creating a tuple:
os.path.splitext("name.fasta")
the created tuple now contains the strings "name" and "fasta".
Then you need to access only the string "name" which is the first element of the tuple:
os.path.splitext("name.fasta")[0]
And then you want to add a new extension to that name:
os.path.splitext("name.fasta")[0]+".aln"
As AnaPana mentioned pathlib is more new and easier in python 3.4 and there is new with_suffix method that can handle this problem easily:
from pathlib import Path
new_filename = Path(mysequence.fasta).with_suffix('.aln')
Using pathlib and preserving full path:
from pathlib import Path
p = Path('/User/my/path')
new_p = Path(p.parent.as_posix() + '/' + p.stem + '.aln')
Sadly, I experienced a case of multiple dots on file name that splittext does not worked well... my work around:
file = r'C:\Docs\file.2020.1.1.xls'
ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
filefinal = file.replace(ext,'')
filefinal = file + '.zip'
os.rename(file ,filefinal)
>> file = r'C:\Docs\file.2020.1.1.xls'
>> ext = '.'+ os.path.realpath(file).split('.')[-1:][0]
>> filefinal = file.replace(ext,'.zip')
>> os.rename(file ,filefinal)
Bad logic for repeating extension, sample: 'C:\Docs\.xls_aaa.xls.xls'

How to replace a part of a File Path in Python

import os.path
original = input(str("Filepath:"))
filename = os.path.basename(original)
print(filename)
target = r'C:\Users\Admin\Desktop\transfer\filename'
path = filename.replace('filename', filename)
print(path)
I have a problem with getting new target path... I need to copy original file and paste it to new directory, that is always the same and the name must stay the same as it was in previous directory, I was trying to do it by code on top but it doesn't work, only thing I need to know is how to replace name of the Path file at the end. (Example: r'C:\Users\Admin\Desktop\Directory2\***' and replace *** with filename of first file)
Considering your code, if you want to change C:\Users\Admin\Desktop\transfer\filename into C:\Users\Admin\Desktop\transfer\{new filename} you need to call replace() function on «target» variable, not on the «filename» variable.
So your code would look something like:
import os.path
original = input(str("Filepath:"))
filename = os.path.basename(original)
target = r'C:\Users\Admin\Desktop\transfer\filename'
path = target.replace('filename', filename)
On entering D:\Documents\program.py, the output is C:\Users\Admin\Desktop\transfer\program.py

Build universal path for all operating systems

This is my code
path = r'C:/Users/user/documents/data'
def new_name(path, keyword, ext="csv"):
return ('\\'.join(path.split("\\")[:-1]) + "\\" + path.split("\\")[-1].split(".")[0] + keyword + "." + ext)
new_path = new_name(path, '_test')
print(new_path)
>>> \C:/Users/user/documents/data_test.csv # Output
C:/Users/user/documents/data_test.csv # What I want
I get a path with a file and I would like to add a keyword to this file. Does this option also exist with Pathlib (or something like that)?
Since this path doesn't work properly on Mac, I would like to build a more universal solution.
The pathlib module (Python 3.4+) is your friend when working with paths in Python.
In special, the class pathlib.Path:
This class represents concrete paths of the system’s path flavour (instantiating it creates either a PosixPath or a WindowsPath).
Which means that you don't have to worry about OS-specific path details such as forward/backward slashes.
So the above example could be rewritten as:
from pathlib import Path
path = Path('C:/Users/user/documents/data')
def new_name(path, keyword, ext="csv"):
return Path(str(path) + keyword + '.' + ext)
new_path = new_name(path, '_test')
print(new_path)
>>> C:/Users/user/documents/data_test.csv
I'd use the os.path.join command in this case
for example:
Assume you are running a script from *C:\temp*
and want to load "file_name=inputfile.json" from ./json folder.
You need to concatenate the paths to get one absolute path to the filename: C:\temp\json\inputfile.json
Code would look like:
from os import path
file_name = "inpoutfile.json"
abs_file_path = os.path.join(os.path.dirname(__file__),"json", file_name)
print (abs_file_path)
result is:
C:\temp\json\inputfile.json

Cut down path name in Python

This is my current code:
directory = "C:/Users/test/Desktop/test/sign off img"
choices = glob.glob(os.path.join(directory, "*.jpg"))
print(choices)
This will return me every single path to all .JPG files inside that specific folder.
As an example, here is the output for the current above code:
['C:/Users/test/Desktop/test/sign off img\\SFDG001 0102400OL - signed.jpg', 'C:/Users/test/Desktop/test/sign off img\\SFDG001 0102400OL.jpg']
How can I get the output to only return the ending of the path?
This is my desire outcome:
['SFDG001 0102400OL - signed.jpg', 'SFDG001 0102400OL.jpg']
Same path, but just the end string is returned.
You can use the os.listdir function:
>>> import os
>>> files = os.listdir("C:/Users/test/Desktop/test/sign off img")
>>> filtered_files = [file for file in files if 'signed' in file]
As you can see in thee docs, os.listdir uses the current directory as default argument, i.e., if you don't pass a value. Otherwise, it will use the path you pass to it.
I recommend using pathlib.Path over os most of the time. Try this, for example:
from pathlib import Path
directory = Path("C:/Users/test/Desktop/test/sign off img")
choices = [path.name for path in directory.glob("*.jpg")]

Python converting url into directory

I am trying to convert a url like "www.example.com/images/dog.png" into directories from the current directory.
So I get a folder named "www.example.com", inside that "images" and finally inside that the file saved as "dog.png"
I've tried using urllib.url2pathname(path) but it keeps appending P:\ to the start of it.
You can use os.makedirs() to create the directory tree, but that will fail if the final directory already exists. So you can test if it exists before attempting to create the directory tree, or use try: ... except OSError:. In Python 3 you can supply an exist_ok parameter to over-ride this behaviour, see the Python docs of os.makedirs for further info.
#!/usr/bin/env python
import os
cwd = os.getcwd()
url = "www.example.com/images/dog.png"
fullname = os.path.join(cwd, url)
path, basename = os.path.split(fullname)
if not os.path.exists(path):
os.makedirs(path)
with open(fullname, 'w') as f:
f.write('test\n')
If your system doesn't support directory names containing periods you can translate them to another character, eg _, like this:
fullname = fullname.replace('.', '_')
(just insert this after the fullname = os.path.join(cwd, url) line).
And as jwilner mentions in the comments, it's more efficient to use
path = os.path.dirname
than path, basename = os.path.split(fullname) if you don't need the base component of the file name (in this example "dog.png").

Categories