I'm trying to access a folder that is in the current directory in which I am writing my code. the folder I am currently in is cs113
I've tried to do
file2 = open("/cs113/studentstoires/Zorine.txt", "r)"
Would someone please tell me whey this doesn't work I've also tried to write the directory name like this:
open("/studentstories/Zorine.txt", "r")
Do I need to import sys and use sys.listdir or os.path? If so can you please give a quick little example how to do this? Thank you in advance.
If it's in the current directory, and it's the directory where you execute the script from, you should write the path without the / up front like so:
file2 = open("studentstories/Zorine.txt", "r")
Related
first post here so sorry if it's hard to understand. Is it possible to shorten the directory in python to the location of the .py file?. For example, if I wanted to grab something from the directory "C:\Users\Person\Desktop\Code\Data\test.txt", and if the .py was located in the Code folder, could I shorten it to "\data\test.txt". I'm new to python so sorry if this is something really basic and I just didn't understand it correctly.
I forgot to add i plan to use this with multiple files, for example: "\data\test.txt" and \data\test2.txt
import os
CUR_FILE = os.path.abspath(__file__)
TARGET_FILE = "./data/test.txt"
print(os.path.join(CUR_FILE, TARGET_FILE))
With this, you can move around your Code directory anywhere and not have to worry about getting the full path to the file.
Also, you can run the script from anywhere and it will work (you don't have to move to Code's location to run the script.
You can import os and get current working directory ,this will give you the location of python file and then you can add the location of folder data and the file stored in that ,code is given below
import os
path=os.getcwd()
full_path1=path+"\data\test.txt"
full_path2=path+"\data\test2.txt"
print(full_path1)
print(full_path2)
I think this will work for your case and if it doesn't work then add a comment
I think that's easy but my script doesn't work. I think it's gonna be easier if I show you what I want: I want a script (in python) which does that:
I have a directory like:
boite_noire/
....helloworld/
....test1.txt/
....test2.txt/
And after running the script I would like something like:
boite_noire/
helloworld/
....test1/
........test1_date.txt
....test2/
........test2_date.txt
and if I add an other test1.txt like:
boite_noire/
helloworld/
....test1/
........test1_date.txt
....test2/
........test2_date.txt
....test1.txt
The next time I run the script:
boite_noire/
helloworld/
....test1/
........test1_date.txt
........test1_date.txt
....test2/
........test2_date.txt
I wrote this script :
But os.walk read files in directories and then create a directory named as the file, and I don't want that :(
Can someone help me please?
You could loop through each file and move it into the correct directory. This will work on a linux system (not sure about Windows - maybe better to use the shutil.move command).
import os
import time
d = 'www/boite_noire'
date = time.strftime('%Y_%m_%d_%H_%M_%S')
filesAll = os.listdir(d)
filesValid= [i for i in filesAll if i[-4:]=='.txt']
for f in filesValid:
newName = f[:-4]+'_'+date+'.txt'
try:
os.mkdir('{0}/{1}'.format(d, f[:-4]))
except:
print 'Directory {0}/{1} already exists'.format(d, f[:-4])
os.system('mv {0}/{1} {0}/{2}/{3}'.format(d, f, f[:-4], newName))
This is what the code is doing:
Find all file in a specified directory
Check the extension is .txt
For each valid file:
Create a new name by appending the date/time
Create the directory if it exists
move the file into the directory (changing the name as it is moved)
I'm new to Python and really want this command to work so I have been looking around on google but I still can't find any solution. I'm trying to make a script that deletes a folder inside the folder my Blender game are inside so i have been trying out those commands:
import shutil
from bge import logic
path = bge.logic.expandPath("//")
shutil.rmtree.path+("/killme") # remove dir and all contains
The Folder i want to delete is called "killme" and I know you can just do: shutil.rmtree(Path)
but I want the path to start at the folder that the game is in and not the full C:/programs/blabla/blabla/test/killme path.
Happy if someone could explain.
I think you are using shutil.rmtree command in wrong way. You may use the following.
shutil.rmtree(path+"/killme")
Look at the reference https://docs.python.org/3/library/shutil.html#shutil.rmtree
Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)
Assuming that your current project directory is 'test'. Then, your code will look like the follwing:
import shutil
from bge import logic
path = os.getcwd() # C:/programs/blabla/blabla/test/
shutil.rmtree(path+"/killme") # remove dir and all contains
NOTE: It will fail if the files are read only in the folder.
Hope it helps!
What you could do is set a base path like
basePath = "/bla_bla/"
and then append the path and use something like:
shutil.rmtree(basePath+yourGamePath)
If you are executing the python as a standalone script that is inside the desired folder, you can do the following:
#!/usr/bin/env_python
import os
cwd = os.getcwd()
shutil.rmtree(cwd)
Hope my answer was helpful
The best thing you could do is use the os library.
Then with the os.path function you can list all the directories and filenames and hence can delete/modify the required folders while extractring the name of folders in the same way you want.
for root, dirnames, files in os.walk("issues"):
for name in dirnames:
for filename in files:
*what you want*
Probably a simple query.. But basically, I have data in directory "/foo/bar/foobar.txt"
and I am working in directory "/some/path/read_foobar.py"..
Now I want to read the file "foobar.txt" but rather than giving full path, I thought of adding /foo/bar/ to the path..
So, added the following at the start of read_foobar.py
import sys
sys.path.append("/foo/bar")
But when I try to read open("foobar.txt","r"), it is not able to find the file?
how do I do this?
Thanks
You can do it like this:
import os
os.chdir('/foo/bar')
f = open('foobar.txt', 'r')
sys.path is used to set the path used to look for python modules. Short of you writing some helper function that has a list of directories to search in when opening a file, I don't believe there is a standard module that provides this functionality.
From what I gathered from here and some quick tests, appending a path to sys.path will make python search in that path when you import a file/module, but not when open-ing it. Let's say we have a file called foo.py in /foo/bar/
import sys
sys.path.append("/foo/bar/")
try:
f = open('foo.py', 'r')
except:
print('this did not work') # this will print
import foo # no problems here
Unfortunately you can't. The PATH environment variable is only used by the operating system to search for executable files, and python uses it (along with the environment variable PYTHONPATH) to search for python modules to import.
You may want to consider setting a symbolic link to that file from your current working directory
ln -s /foo/bar/foobar.txt /some/path/foobar.text
Hi I am currently a beginner to the python language, it is also my first language too. I need some help I am finding it difficult to know what to use to generate permanent directories sub directories and files, for eg; I want the path to generate whatever path i enter if the directories etc. don't exist, i want them created, so I enter C:\user\python\directory\sub-directory\file, then i cant workout what i should import to do the following job.
I am using Python 3.2, any advice?
You can do:
import os
os.makedirs('a/b/c', exist_ok=True)
http://docs.python.org/py3k/library/os.html
f = open("c:\file\path","w")
f.write("content of file")
First, you open the file, storing it in variable f.
You then write to it, using f.write()
Python will create the file and path if it does not exist, I think. (I am sure I've done this before, but I can't remember)
When you have finished using the file, you should use
f.close()
to close the file safely.