Error, file already exists. Python - 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?

Related

Been trying to copy folders and files using shutil.tree() function in python but brings FileExistsError

I have tried to use shutil module in python. The shutil.copytree fails to copy folders and brings FileExistsError. I have tried it using different files but it still fails.Please check
import shutil
from pathlib import Path
p = Path(r"C:\Users\rapid\OneDrive\Desktop")
shutil.copytree(p/"folder_1", p/"folder_2")
Please check for the error image
I tried the code myself and works fine the first time.
After the destination folder (in your case folder_2) already created shutil can't create it again and it fails. So you can either delete the destination folder manually or using shutil.rmtree.
Good Luck!
All credit to Timus. He provided the solution on the comment section. Just used
shutil.copytree(p/"folder_1", p/"folder_2", dirs_exist_ok=True)
It works fine. Thanks Timux

The 'os' module in Python says "No such file or directory" even when there definitely is one

I am trying to open an .npy file. However, Python keeps saying that there exists no such file or directory, even when there is one...
To make sure that it isn't an issue of giving correct path names, I changed my directory to the folder that contains the .npy file that I want. Then used list.dir() and used it to use np.load (the code is below):
os.chdir(filename_dir) #filename_dir is the directory I want to get to that contains the npy file I want)
the_path=os.path.join(os.getcwd()+os.listdir()[-1]) #i.e. I did this to make sure that the directory is correct
data=np.load(the_path)
However, I got the error, [Errno 2] No such file or directory: .......
The error occurs when I try np.load. I couldn't understand this because I explicitly made the path the_path from what Python says exists.
I think this is the problem...
Windows (by default) has a maximum path length of 260 characters. The absolute path to this file exceeds that limit. The filename alone is 143 characters.
It looks as though even if you try to access the file using a relative path (i.e., chdir() to the appropriate folder then specify just the filename), numpy is probably working out the absolute path then failing.
You have said that renaming the file to something much shorter solves the problem but is impractical due to the high numbers of files that you need to process.
There is a Windows Registry key that can be modified to enable long pathnames: Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled
Changing that may help.
Or you could buy a Mac
Try adding r. For example,
file_path = r"filePath"
This may work...

Importing a file using pandas

Data visualisation: I want to import a file using pandas. I assigned a variable and file name given is correct but it shows a error message as file does not exist
Code: sample_data = pd.read_csv('sample_data.csv')
You're probably in the wrong working directory. Run os.getcwd() to check. If so, you can either change working directories with os.chdir() or give an absolute path to the file instead of a relative path.
If you're already in the right working directory, run os.listdir() to make sure the file is actually there.
Ok, in this case, what you will have to do is get the path file by right-clicking on the file and going to properties(Windows, don't know about Mac). Then just copy the file path and paste it instead of the file name. So for now, it should be something like this(as I don't know your file path):
sample_data = pd.read_csv('C:\Users\SVISHWANATH\Downloads\datasets')
Now, after the last folder, give in your file name. So now, it should look like this:
sample_data = pd.read_csv('C:\Users\SVISHWANATH\Downloads\datasets\sample_data.csv')
However, this will still not work as the slashes need to be the other way. Because of this, there will have to be an r before the quotes.
sample_data = pd.read_csv(r'C:\Users\SVISHWANATH\Downloads\datasets\sample_data.csv')
Now this should work as all the requirements are met.
You need to store the .csv file in a folder where the actual program is stored, otherwise you have to give a proper path to the file:
sample_data = pd.read_csv('filepath')

How to read a file whose name includes '/' in 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.

Errno13, Permission denied when trying to read file

I have created a small python script. With that I am trying to read a txt file but my access is denied resolving to an no.13 error, here is my code:
import time
import os
destPath = 'C:\Users\PC\Desktop\New folder(13)'
for root, dirs, files in os.walk(destPath):
f=open(destPath, 'r')
.....
Based on the name, I'm guessing that destPath is a directory, not a file. You can do a os.walk or a os.listdir on the directory, but you can't open it for reading. You can only call open on a file.
Maybe you meant to call open on one or more of the items from files
1:
I take it you are trying to access a file to get what's inside but don't want to use a direct path and instead want a variable to denote the path. This is why you did the destPath I'm assuming.
From what I've experienced the issue is that you are skipping a simple step. What you have to do is INPUT the location then use os.CHDIR to go to that location. and finally you can use your 'open()'.
From there you can either use open('[direct path]','r') or destPath2 = 'something' then open(destPath2, 'r').
To summarize: You want to get the path then NAVIGATE to the path, then get the 'filename' (can be done sooner or not at all if using a direct path for this), then open the file.
2: You can also try adding an "r" in front of your path. r'[path]' for the raw line in case python is using the "\" for something else.
3: Try deleting the "c:/" and switching the / to \ or vice versa.
That's all I got, hope one of them helps! :-)
I got this issue when trying to create a file in the path -C:/Users/anshu/Documents/Python_files/Test_files . I discovered python couldn't really access the directory that was under the user's name.
So, I tried creating the file under the directory - C:/Users/anshu/Desktop .
I was able to create files in this directory through python without any issue.

Categories