I am trying to set the folder_out to the subfolder where the source .csv is found.
So I have many folders and subfolders in the main Processing folder.
I want to save the the .csv file in the same folder as where it has found the file.
When I use the root, with pathlib, is that possible?
And, I am getting now back IOError: [Errno 13] Permission denied: 'D:\Processing\DG_Boeblingen-..... etc.
So it found the file, but can't write.
I am in Python 2.7 and using 'wb' to write.
how I set the Path and rb an wb, is using wb and rb, correct?
folder_in = Path(r'D:\Processing')
folder_out = Path(r'.')
folder_in_traj = Path(r'D:\Processing')
folder_out_traj = Path(r'.')
for incsv in folder_in.iterdir():
outcsv = folder_out.joinpath('0new'+incsv.name)
with open(str(incsv), 'rb') as input, open(str(outcsv), 'wb') as output:
You are trying to save a file in root directory for which you would need sudo prviliges so if you execute the python script as super user then you should not see this issue.
I am kind of confused as to what you are trying to do here. Are you trying to output the CSV to root? In that case I think you are using Path(r'root') wrong. If you look at the documentation for pathlib, there is a class called PurePath with a method called root. You can use this to return the root.
Passing in root to Path will just return root as the path. You can try using . instead of root which might resolve to the root.
Related
I don't know what's wrong here, all I'm trying to do is to open this file, but it says it can't find such a file or directory, however as I have highlighted on the side, the file is right there. I just want to open it. I have opened files before but never encountered this. I must have missed something, I checked online, and seems like my syntax is correct, but I don't know.
I get the same error when I try with "alphabetical_words" which is just a text file.
When open() function receives a relative path, it looks for that file relative to the current working directory. In other words: relative to the current directory from where the script is run. This can be any arbitrary location.
I guess what you want to do is look for alphabetical.csv file relative to the script location. To do that use the following formula:
from pathlib import Path
# Get directory of this script
THIS_DIR = Path(__file__).absolute().parent
# Get path of CSV file relative to the directory of this script
CSV_PATH = THIS_DIR.joinpath("alphabetical.csv")
# Open the CSV file using a with-block
with CSV_PATH.open(encoding="utf-8") as csvfile:
pass # Do stuff with opened file
You need to import csv. Then you can open the file as a csv file. For example,
with open ("alphabetical.csv", "r") as csvfile:
Then you can use the file.
Make sure the file is in your cwd.
Currently, I have a folder structure as below in my python project and I wanted to open the sample.json file in the run.py file.
parent_folder
--subfolder1
--sub_sub_folder1
--sub_sub_sub_folder1
--run.py
-- sub_sub_folder2
--sample.json
So I have tried as below
file_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'../../sub_sub_folder2/sample.json')
file_content= open(file_dir)
But I am getting error as below
[Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/sub_sub_folder2/sample.json'
Could some please help me?
You can first change the directory into where your python program exists through os.chdir:
os.chdir(os.path.dirname(os.path.abspath(__file__)))
And then, specify the path of your target file:
file_dir = '../../sub_sub_folder2/sample.json'
Your way to do it seems ugly to me, but it should work. Are you sure, the folder structure is as you describe it? The ErrorMessage implies that the parent folder of your project is /usr/local/lib/python3.6/ - that most probably not true.
A cleaner way would make use of pathlib
from pathlib import Path
path_script = Path(__file__)
path_ancestor_common = path_script.parents[2]
path_json = path_ancestor_common.joinpath(
'sub_sub_folder2', 'sample.json')
I'm trying to build a file transfer system with python3 sockets. I have the connection and sending down but my issue right now is that the file being sent has to be in the same directory as the program, and when you receive the file, it just puts the file into the same directory as the program. How can I get a user to input the location of the file to be sent and select the location of the file to be sent to?
I assume you're opening files with:
open("filename","r")
If you do not provide an absolute path, the open function will always default to a relative path. So, if I wanted to open a file such as /mnt/storage/dnd/5th_edition.txt, I would have to use:
open("/mnt/storage/dnd/4p5_edition","r")
And if I wanted to copy this file to /mnt/storage/trash/ I would have to use the absolute path as well:
open("/mnt/storage/trash/4p5_edition","w")
If instead, I decided to use this:
open("mnt/storage/trash/4p5_edition","w")
Then I would get an IOError if there wasn't a directory named mnt with the directories storage/trash in my present folder. If those folders did exist in my present folder, then it would end up in /whatever/the/path/is/to/my/current/directory/mnt/storage/trash/4p5_edition, rather than /mnt/storage/trash/4p5_edition.
since you said that the file will be placed in the same path where the program is, the following code might work
import os
filename = "name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
Its pretty simple just get the path from user
subpath = raw_input("File path = ")
print subpath
file=open(subpath+str(file_name),'w+')
file.write(content)
file.close()
I think thats all you need let me know if you need something else.
like you say, the file should be in the same folder of the project so you have to replace it, or to define a function that return the right file path into your open() function, It's a way that you can use to reduce the time of searching a solution to your problem brother.
It should be something like :
import os
filename = "the_full_path_of_the_fil/name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
then you can use the value of the f variable as a path to the directory of where the file is in.
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.
In python I´m creating a file doing:
f = open("test.py", "a")
where is the file created? How can I create a file on a specific path?
f = open("C:\Test.py", "a")
returns error.
The file path "c:\Test\blah" will have a tab character for the `\T'. You need to use either:
"C:\\Test"
or
r"C:\Test"
I recommend using the os module to avoid trouble in cross-platform. (windows,linux,mac)
Cause if the directory doesn't exists, it will return an exception.
import os
filepath = os.path.join('c:/your/full/path', 'filename')
if not os.path.exists('c:/your/full/path'):
os.makedirs('c:/your/full/path')
f = open(filepath, "a")
If this will be a function for a system or something, you can improve it by adding try/except for error control.
where is the file created?
In the application's current working directory. You can use os.getcwd to check it, and os.chdir to change it.
Opening file in the root directory probably fails due to lack of privileges.
It will be created once you close the file (with or without writing). Use os.path.join() to create your path eg
filepath = os.path.join("c:\\","test.py")
The file is created wherever the root of the python interpreter was started.
Eg, you start python in /home/user/program, then the file "test.py" would be located at /home/user/program/test.py
f = open("test.py", "a") Will be created in whatever directory the python file is run from.
I'm not sure about the other error...I don't work in windows.
The besty practice is to use '/' and a so called 'raw string' to define file path in Python.
path = r"C:/Test.py"
However, a normal program may not have the permission to write in the C: drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.
Use os module
filename = "random.txt"
x = os.path.join("path", "filename")
with open(x, "w") as file:
file.write("Your Text")
file.close