I know this may sound really stupid, but how can I move a file in a directory a user browsed to ( I named mine filedir) to the current directory I am in?
for example: I have a file called "pages.html" in "C:\webs". How can I move that file to the current working directory "."?
This is my code:
shutil.move(filedir, "*.*")
#I got errors using this code..
Is there another way to say current directory, other than "." ?
The second argument of shutil.move specifies a directory, not a glob mask:
import os.path
shutil.move(os.path.join(filedir, "pages.html"), os.getcwd())
should work.
It would be very helpful if you posted the error message and the complete traceback. However, to get the current working directory you can use os.getcwd(). As long as filedir points to a file and not the directory this should work.
filedir = r"C:\webs\pages.html"
shutil.move(filedir, os.getcwd())
Related
I am trying to run a Streamlit app importing pickle files and a DataFrame. The pathfile for my script is :
/Users/myname/Documents/Master2/Python/Final_Project/streamlit_app.py
And the one for my DataFrame is:
/Users/myname/Documents/Master2/Python/Final_Project/data/metabolic_syndrome.csv
One could reasonably argue that I only need to specify df = pd.read_csv('data/df.csv') yet it does not work as the Streamlit app is unexpectedly not searching in its directory:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/myname/data/metabolic_syndrome.csv'
How can I manage to make the app look for the files in the good directory (the one where it is saved) without having to use absolute pathfiles ?
you can use os.getcwd() to get the Current Working Directory. Read up on what this means exactly, fe here
See the sample script below on how to use it. I'm using os.sep for OS agnostic filepath separators.
import os
print(os.getcwd())
relative_path = "data"
full_path = f"{os.getcwd()}{os.sep}{relative_path}"
print(full_path)
filename = "somefile.csv"
full_file_path = f"{full_path}{os.sep}{filename}"
print(full_file_path)
with open(full_file_path) as infile:
for line in infile.read().splitlines():
print(line)
In which directory are you standing when you are running your code?
From your error message I would assume that you are standing in /Users/myname/ which makes python look for data as a subdirectory of /Users/myname/.
But if you first change directory to /Users/myname/Documents/Master2/Python/Final_Project and then run your code from there I think it would work.
I am new to VSCODE. I opened a text file via vscode and entered some details. Where can I find the file?
f=open('story.txt','w')
f.write('my name is')
f.write('my age is')
f.close()
f=open('story.txt', 'r')
print(f.readline())
f.close()
this is the output
However I cannot find 'story.txt' in file explorer. I used another text editor and then error came as file not found. but when i reopened the file in vs code I was getting a proper output.
From the screenshot you supplied it looks like you are running the script from C:\Users\<YourName>, then this is where your story.txt file will be.
To specify another location you need to supply the open() method with a full path
Also, it's best practice to close the file before opening it again for reading. also, you might want to use a context manager to help you with this
If you want your file saved in the directory of your script, you can use os and __file__ to locate your script's directory and use that.
import os
my_dir = os.path.dirname(__file__)
new_path = os.path.join(my_dir, 'story.txt')
print(new_path)
os documentation
__file__ explained
When you run python script it will execute from the current working directory by defaut.
If you want to be sure where your file will be, you may pass the complete file path instead of file name only (eg: C:\\filepath\\filename.txt)
or you can move to the desired directory before read/write with os.chdir(filepath)
If you don't know where the script is running you can use os.getcwd() to get this directory from your code
import os
print(os.getcwd()) #will show the current working directory
os.chdir("c:\\") #will move to C:\ directory
f=open('story.txt','w')
f.write('my name is')
f.write('my age is')
f=open('story.txt', 'r')
print(f.readline())
f.close()
When you create a file with Python, the file will be create in the same folder as your script. So, if your folder all_python_scripts contains your script, your file story.txt will be created in this folder. Try to search your file in the script's folder.
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.
If I try to rename files in a directory, for some reason I get an error.
I think the problem may be that I have not inserted the directory in the proper format ?
Additional info:
python 2 &
linux machine
OSError: [Errno 2] No such file or directory
Though it prints the directories content just fine. What am I doing wrong?
import os
for i in os.listdir("/home/fanna/Videos/strange"):
#print str(i)
os.rename(i, i[:-17])
os.rename() is expecting the full path to the file you want to rename. os.listdir only returns the filenames in the directory. Try this
import os
baseDir = "/home/fanna/Videos/strange/"
for i in os.listdir( baseDir ):
os.rename( baseDir + i, baseDir + i[:-17] )
Suppose there is a file /home/fanna/Videos/strange/name_of_some_video_file.avi, and you're running the script from /home/fanna.
i is name_of_some_video_file.avi (the name of the file, not including the full path to it). So when you run
os.rename(i, i[:-17])
you're saying
os.rename("name_of_some_video_file.avi", "name_of_some_video_file.avi"[:-17])
Python has no idea that these files came from /home/fanna/Videos/strange. It resolves them against the currrent working directory, so it's looking for /home/fanna/name_of_some_video_file.avi.
I'm a little late but the reason it happens is that os.listdir only lists the items inside that directory, but the working directory remains the location where the python script is located.
So to fix the issue add:
os.chdir(your_directory_here)
just before the for loop where your_directory_here is the directory you used for os.listdir.