I used r' in front of the string so that Python doesn't treat the backslashes as escape sequences.
df.to_excel(r'C:\Users\A\Desktop\Data\file.xlsx', index = False) #exporting to excelfile named "file.xlsx"
However, this time I need the filename to be a variable instead.
I usually format it by using F-string but I can't combine the r' and f' together. It doesn't work
df.to_excel(r'f'C:\Users\A\Desktop\Data\{filename}.xlsx'', index = False)
How can i solve this? Thanks
I would suggest using either pathlib or os.path module in case you are working with paths and want your project to be compatible with different OS.
For pathlib, you can use the following snippet. Note that the forward slashes will be automatically converted in the correct kind of slash for the current OS.
from pathlib import Path
data_folder = Path("C:/Users/A/Desktop/Data/")
file_name = 'myname.xlsx'
file_path = data_folder / file_name
df.to_excel(file_path, index = False)
The answer to your current question would be using string concatenation. Something like this:
df.to_excel(r'C:\Users\A\Desktop\Data\' + f'{filename}.xlsx', index = False)
You don't have to place each within quote marks- 1 set will do:
fr'C:\Users\A\Desktop\Data\{filename}.xlsx'
Quotes are wrong. You can use it like this.
df.to_excel(rf'C:\Users\A\Desktop\Data\{filename}.xlsx', index = False)
Related
I am trying to replace a string here in Python.
This is my Input -
link = (r"C:\dell\Documents\Ms\Realm")
I want my output to be like this:
C:/dell/Documents/Ms/Realm
I tried the replace method it didn't work.
the code tried:
link = (r"C:\dell\Documents\Ms\Realm")
link.replace("\","/")
In Python strings, the backslash "\" is a special character, also called the "escape" character. You need to add second backslash to "escape" it and use in string search.
link.replace("\\", "/")
There's nothing wrong with that Windows path. There's no reason to replace anything. A real improvement would be to use pathlib instead of raw strings:
from pathlib import Path
link = Path(r"C:\dell\Documents\Ms\Realm")
That would allow you to construct paths from parts using, eg joinpath, get the parts of the path with parts, the name with name, directory with parent etc.
var filePath=link.joinpath("some_file.txt")
print(filePath)
-------------------
C:\dell\Documents\Ms\Realm\some_file.txt
and more
>>> print(link.parts)
('C:\\', 'dell', 'Documents', 'Ms', 'Realm')
>>> print(link.parent)
C:\dell\Documents\Ms
Or search for files in a folder recursively:
var files=(for file in link.rglob("*.txt") if file.is_file())
I'm trying to open a file like this:
with open(str(script_path) + '\\description.xml', 'w+') as file:
where script_path is equal to this:
script_path = os.path.dirname(os.path.realpath(__file__)) + '\\.tmp')
When I run this I get an error that there is no such file or directory because when it tries to open the file it sees the whole path as a string, including the escape strings. Is there any way around this?
Obviously .replace() won't work here as it won't replace the escape string. Hoping there is a clever way to do this within the os module?
Not really sure why you're adding two backslashes. You can simply create the path using a single forward slash (Linux based) or backslash (win). Something like this:
script_path = os.path.dirname(os.path.realpath(__file__)) + '/tmp/description.xml'
However, better way to achieve this would be to use os.path.join as suggested by nomansland008.
>>> import os
>>> parent_dir = "xyz"
>>> dir = "foo"
>>> file_name = "bar.txt"
>>> os.path.join(parent_dir, dir, file_name)
'xyz/foo/bar.txt'
You won't have to bother about whether the string has slash(or not). It will be taken care by join.
In your case it can simply be:
os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tmp', 'description.xml')
Should work, provided the files and directories exist.
a='C:/Users/me/Documents/PythonProjects/opencv/Train\11\00011_00014_00018.png'
I am running a for loop with variables such as a, that are strings.
I intend to obtain the number 11 from the string above.
Using a.replace('\\,'/') , i get the exact same string back , that is, 'C:/Users/me/Documents/PythonProjects/opencv/Train\11\00011_00014_00018.png'
the only way i got it to work was with r/'C:/Users/me/Documents/PythonProjects/opencv/Train\11\00011_00014_00018.png'.replace('\\','/') but that does not work with variables i.e
r'a'.replace('\\','/')
its not like f-strings whereby i can parse variables as such f'{a}'
I would instead recommend using os.path if your intention is to clean up or mutate filesystem paths
>>> import os
>>> a='C:/Users/me/Documents/PythonProjects/opencv/Train\11\00011_00014_00018.png'
>>> os.path.normpath(a)
'C:\\Users\\me\\Documents\\PythonProjects\\opencv\\Train\t\x0011_00014_00018.png'
Using os.path for path manipulation will generally behave correctly on different operating systems without you having to manually modify slashes, drive names, etc.
Thanks it worked !
root_dir = 'C:/Users/me/Documents/PythonProjects/opencv/Train'
all_img_paths = glob.glob(os.path.join(root_dir, '**.png'))
for img_path in all_img_paths:
try:
img = preprocess_img(io.imread(img_path))
label = get_class(img_path)
to:
all_img_paths = glob.glob(os.path.join(os.path.normpath(root_dir), '**.png'))
np.random.shuffle(all_img_paths)
I am creating a format string that is different based on class, that is used to generate a filename by a generic class method. I'm using the Python 3.4+ pathlib.Path module for object-oriented file I/O.
In building this string, the path separator is missing, and rather than just put the windows version in, I want to add a platform independent file separator.
I searched the pathlib docs, and answers here about this, but all the examples assume I'm building a Path object, not a string. The pathlib functions will add the correct separator in any string outputs, but those are actual paths - so it won't work.
Besides something hacky like writing a string and parsing it to figure out what the separator is, is there a way to directly get the current, correct file separator string?
Prefer an answer using pathlib.Path, rather than os or shutil packages.
Here's what the code looks like:
In the constructor:
self.outputdir = Path('drive:\\dir\\file')
self.indiv_fileformatstr = str(self.outputdir) + '{}_new.m'
In the final method used:
indiv_filename = Path(self.indiv_fileformatstr.format(topic))
This leaves out the file separator
There is nothing public in the pathlib module providing the character used by the operating system to separate pathname components. If you really need it, import os and use os.sep.
But you likely don't need it in the first place - it's missing the point of pathlib if you convert to strings in order to join a filename. In typical usage, the separator string itself isn't used for concatenating path components because pathlib overrides division operators (__truediv__ and __rtruediv__) for this purpose. Similarly, it's not needed for splitting due to methods such as Path.parts.
Instead of:
self.indiv_fileformatstr = str(self.outputdir) + '{}_new.m'
You would usually do something like:
self.indiv_fileformatpath = self.outputdir / '{}_new.m'
self.indiv_fileformatstr = str(self.indiv_fileformatpath)
The platform-independent separator is in pathlib.os.sep
Solution using wim's answer
Based on wim's answer, the following works great:
Save the format string in the Path object
When needing to substitute into the templated filename in the future, just use str(path_object) to get the string back out.
import pathlib
# Start with following, with self.outputdir as pathlib.Path object
outputdir = 'c:\\myfolder'
file_template_path = outputdir / '{}_new.m'
# Then to make the final file object later (i.e. in a child class, etc.)
base_filename_string = 'myfile'
new_file = pathlib.Path(str(file_template).format(base_filename_string))
This creates:
pathlib.Path("c:\\myfolder\myfile_new.m")
Creating the template with prefix/postfix/etc.
If you need to apply other variables, you can use 2 levels of formatting to apply specialized prefixes/postfixes, etc., then store the final template in a Path object, as shown above.
When creating 2 levels of formatting, use double brackets where the first level formatter should just create a single bracket and not try to interpret a tag. i.e. {{basename}} becomes just {basename} without any variable substitution.
prefix = 'new_'
postfix = '_1'
ext = 'txt'
file_template_path = outputdir / f'{prefix}{{}}{postfix}.{ext}'
which becomes a path object with the following string:
$ file_template_path
pathlib.Path("c:\\myfolder\new_{}_1.txt")
I have a string from which I would like to extract certain part. The string looks like :
E:/test/my_code/content/dir/disp_temp_2.hgx
This is a path on a machine for a specific file with extension hgx
I would exactly like to capture "disp_temp_2". The problem is that I used strip function, does not work for me correctly as there are many '/'. Another problem is that, that the above location will change always on the computer.
Is there any method so that I can capture the exact string between the last '/' and '.'
My code looks like:
path = path.split('.')
.. now I cannot split based on the last '/'.
Any ideas how to do this?
Thanks
Use the os.path module:
import os.path
filename = "E:/test/my_code/content/dir/disp_temp_2.hgx"
name = os.path.basename(filename).split('.')[0]
Python comes with the os.path module, which gives you much better tools for handling paths and filenames:
>>> import os.path
>>> p = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> head, tail = os.path.split(p)
>>> tail
'disp_temp_2.hgx'
>>> os.path.splitext(tail)
('disp_temp_2', '.hgx')
Standard libs are cool:
>>> from os import path
>>> f = "E:/test/my_code/content/dir/disp_temp_2.hgx"
>>> path.split(f)[1].rsplit('.', 1)[0]
'disp_temp_2'
Try this:
path=path.rsplit('/',1)[1].split('.')[0]
path = path.split('/')[-1].split('.')[0] works.
You can use the split on the other part :
path = path.split('/')[-1].split('.')[0]