You are not logged in.
Pages: 1
I am writing a nifty little program, but this is my first time ever using Python. Can anyone tell me if this works?
Question 1: Do I need to define a variable as GLOBAL if I want to access a variable outside of a function (without changing it)? Or, do I only need to define a variable as global if I want to change it outside of the function? I don't fully understand the scope of variables.
Will this code work for checking if a file exists?
## Using a function,
## Test a directory/file and see if it exists, if it exists set a variable equal to the directory/file
def checkfile():
file1 = os.access('~/file.txt')
if file1 == 1:
print "file1 exists\n"
#### Main Program
checkfile()
return 0
edit:
PS, I am coding at work in my email without the use of a compiler or anything, I am simply coding a lot and going to test it when I get home. I don't have access to anything at work. It would be nice to know if it would run tho, before I go too far
Last edited by Google (2010-06-15 04:12:12)
Offline
Perhaps you should try your namesake first for questions such as this?
http://lmgtfy.com/?q=python+check+if+file+exists
import os.path
if os.path.isfile(filename):
...
Offline
Ahh, that sounds more simple. I was reading a guide that had these:
os.F_OK: test the existence of path
os.R_OK: tests if path exists and is readable
os.W_OK: tests if path exists and is writable
os.X_OK: tests if path exists and is executable
As well as others, but that seems more simple! Thanks~
Offline
Variables of functions are private. When you need it outside you should use a return statement like that:
# First part is the proof that variables are private
def some():
...: a=""
...: a="ssss"
...:
...:
In [2]: some()
In [3]: a
---------------------------------------------------------------------------
<type 'exceptions.NameError'> Traceback (most recent call last)
/home/simon/Downloads/<ipython console> in <module>()
<type 'exceptions.NameError'>: [b]name 'a' is not defined[/b]
#This is how to do it the rightway
In [4]: def some():
a=""
a="ssss"
...: return a
...:
In [7]: b=some()
In [8]: print b
ssss
In [9]:
Dont feel distracted by the ln[1] stuff this is just the output of my shell
{ Github } {Blog and other stuff }
Offline
Sidenote: Usually it's better to just try to use the file and catch the exception if it doesn't work, instead of explicitly checking for the 200 things that can prevent you from using the file.
Evil #archlinux@libera.chat channel op and general support dude.
. files on github, Screenshots, Random pics and the rest
Offline
import os
dir = ""; # this is your dir
if not os.path.exists(dir):
#do something
else:
#do something
Offline
Pages: 1