How to read a file whose name includes '/' in python? - python

Now I have a file named Land/SeaMask and I want to open it, but it cannot be recognized as a filename by programme, but as a directory, how to do it?

First of all I recommend you to find out how Python interpreter displays yours file name. You can do this simply using os built-in module:
import os
os.listdir('path/to/directory')
You'll get a list of directories and files in directory you passed as argument in listdir method. In this list you can find something like Land:SeaMask. After recognizing this, open('path/to/Land:SeaMask') will work for you.

Related

Why does my code delete everything in the folder?

I wrote code to detect all the .exe files in a directory but instead it deletes everything in the folder. How can I change the code to make it delete only the .exe files?
import os
import shutil
dir_name = "/Users/plapl/Downloads/"
source = os.listdir("/Users/plapl/Downloads/")
for files in source:
if files.endswith(".exe"):
shutil.rmtree(dir_name, files)
You can only delete directories with shutil.rmtree but not files (See https://docs.python.org/3/library/shutil.html#shutil.rmtree).
You should use pathlib or os instead.
os.remove(f'{dir_name}/{files}')
pathlib.Path(f'{dir_name}/{files}').unlink()
shutil.rmtree removes the entire directory specified by its first argument. The second argument to shutil.rmtree is ignore_errors, telling the function whether to ignore errors that occur. It is not a file to remove.
shutil.rmtree is a completely inappropriate tool for the job you want to do. You need something like os.remove.

Save a CSV in same directory as python file, using 'to_csv' and 'os.path'?

I want this line to save the csv in my current directory alongside my python file:
df.to_csv(./"test.csv")
My python file is in "C:\Users\Micheal\Desktop\VisualStudioCodes\Q1"
Unfortunately it saves it in "C:\Users\Micheal" instead.
I have tried import os path to use os.curdir but i get nothing but errors with that.
Is there even a way to save the csv alongside the python file using os.curdir?
Or is there a simpler way to just do this in python without importing anything?
import os
directory_of_python_script = os.path.dirname(os.path.abspath(__file__))
df.to_csv(os.path.join(directory_of_python_script, "test.csv"))
And if you want to read same .csv file later,
pandas.read_csv(os.path.join(directory_of_python_script, "test.csv"))
Here, __file__ gives the relative location(path) of the python script being runned. We get the absolute path by os.path.abspath() and then convert it to the name of the parent directory.
os.path.join() joins two paths together considering the operating system defaults for path seperators, '\' for Windows and '/' for Linux, for example.
This kind of an approach should work, I haven't tried, if does not work, let me know.

Error, file already exists. Python

When I am using shutil, I get an unexpected error:
System error 183. Cannot create file when that file already exists
I am using this:
shutil.copytree(src,dst)
src,dst are paths to my directories which I would like to copy. Names are different. For example:
src = 'D:\test\tmp\dir1'
dst = 'D:\test\tmp\dir2'
I know, I could delete dir2 and everything is ok, but I would like to do it without this, is it possible with shutil ?
The document for shutil specifically says that the destination directory must not exist. This happens because it makes a os.makedirs(dst). If you want to append files it could be useful if you used shutil.copyfile.
I am not sure if using shuthil is possible here. Perhaps you can save as a new file?

Rename files using python

I want to rename a file from say {file1} to {file2}. I read about os.rename(file1,file2) in python and is able to do so.
I succeeded only when the the file is placed in the same folder as python script, so I want to ask how can we rename files of other folders i.e. different folder than the one in which python script is placed.
Just use the full path, instead of the relative path:
oldFile = 'C:\\folder\\subfolder\\inFile.txt'
newFile = 'C:\\foo\\bar\\somewhere\\other\\outFile.txt'
os.rename(oldFile, newFile)
To get the double-slash behavior, you can do the following
import os
oldFile = r'C:\folder\subfolder\inFile.txt' # note the r character for raw string
os.path.normpath(oldFile)
Output
'C:\\folder\\subfolder\\inFile.txt'
As others have noted, you need to use full path.
On the other note, take a look at shutil.move documentation, it can also be used for renaming.

Running bash scripts within newly created folders based on file names

I'm not sure even where to start.
I have a list of output files from a program, lets call them foo. They are numbered outputs like foo_1.out
I'd like to make a directory for each file, move the file to its directory, run a bash script within that directory, take the output from each script, copy it to the root directory as a concatenated single file.
I understand that this is not a forum for "hey, do my work for me", I'm honestly trying to learn. Any suggestions on where to look are sincerely appreciated!
Thanks!
You should probably look up the documentation for the python modules os - specifically os.path and a couple of others - and subprocess which can be found here and here respectively.
Without wanting to do it all for you as you stated - you'll be wanting to do something like:
for f in filelist:
[pth, ext] = os.path.splitext(f)
os.mkdir(pth)
out = subprocess.Popen(SCRIPTNAME, stdout=...)
# and so on...
To get a list of all files in a directory or make folders, check out the os module. Specifically, try os.listdir and os.mkdir
To copy files, you could either manually open each file, copy the contents to a string, and rewrite it to a different file. Alternatively, look at the shutil module
To run bash scripts, use the subprocess library.
All three of those should be a part of python's standard library.

Categories