
Untitled
By: a guest on
May 8th, 2012 | syntax:
Python | size: 1.60 KB | hits: 11 | expires: Never
#Enable the os module
import os
#detect the OS if possible
print "Your running " + os.name
#print the current directory
print "You are currently at " + os.getcwd();
print "**********************************************"
#here are the files inside your current location
print "Here are your files in your working directory."
for i in os.listdir(os.curdir):
print i
print "**********************************************"
#show the file connector for your file system
print "Your file seperator is:" + os.path.join(" "," ")
print "**********************************************"
#now for something advanced use the current directory, iterate through and distinguish files from folders
for i in os.listdir(os.curdir):
cur_item = os.path.join(os.getcwd(),i)
if(os.path.isdir(cur_item)):
print i + " <- Directory"
elif (os.path.isfile(cur_item)):
print i + " <- File"
else: #the item may be a link or other special structure
print i + " is not a file nor directory."
# now lets create and delete some data
print "Creating a file "
my_file = open("greets","w")
my_file.write("This is the first line of the greets file")
my_file.close()
my_file = open("greets","r")
print my_file.readline()
my_file.close()
os.remove("greets")
print "Deleted file"
#make a directory os.makedirs will make intermedite directories os. mkdir doesn't
os.mkdir("MyDirectory")
#delete it now only works for empty directories
# to tear out a whole directory tree, shutil.rmtree can be used
os.rmdir("MyDirectory")
#You can walk an entire directory tree using os.path.walk but no use here...