Showing posts with label File Handling. Show all posts
Showing posts with label File Handling. Show all posts

Sunday, April 15, 2012

File Handling In Python IV

Hello everyone, this post would not be a long one, as all the basics has been discussed about file handling.

This is just a quick review of some more File Handling Module that I could not relate to the earlier posts.

Lets get started.

>>> import os
>>> os.name
'nt'
>>> import sys
>>> sys.platform <--More Defined Way To Know About a Host OS
'win32'
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
>>> sys.version
'2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]'
>>> sys.winver
'2.7'
>>> sys.subversion
('CPython', '', '') <--Python is Officially known as CPython, other version is Jython.
>>> sys.api_version
1013
>>> sys.getwindowsversion()
sys.getwindowsversion(major=5, minor=1, build=2600, platform=2, service_pack='Service Pack 2')
>>> sys.getsizeof('C:/files')
29
>>>

Play around with the sys module, type help(sys.any_method_of_sys) To get a detailed report of the Functions.

Well, Some Of You now may be thinking, how to handle some other type of file like an Image File, or say pdf, well, for these, Pythons Inbuilt Library is not enough, You have to go out on the web, to search for the Modules.

Make a Note Here, Whenever You Use Modules from the web, make sure to check that the Module is coded for Python 2 series, because Python 3 has got different syntax.

1. For Images: You need to look for PIL(Python Imaging Library) Take help of Google, as I dont want to spoon feed for everything.

2. MS Office: You need a Module named pywin32, or Python Office(especially meant for excel worksheets)

3. PDF: You need a Module named gfx, found under swftools

And a lot more are there, remember, Python is kinda open source, where codes are developed by any one and everyone. But before using any Module, make sure You use a Module from a trusted site, one good source is stackoverflow.

Now, do you remember I said when we create our own Modules we save it in places where Python looks for, one place i mentioned was Pythons root folder. There is one place and recommended as a standard Pythonist, you should always save the modules in site-packages. Example in my case its:

C:\Python27\Lib\site-packages, to verify, on the Python Shell, click on File>>Path Browser>>Expand the [+] C:\Python27\Lib\site-packages, and you should be able to see any new module that you import there.

Okay, so this was pretty much that you need to fire up your Python Instinct, hope this was helpful, Keep Practicing.

Don't forget to check my next post.

Thank You!

Saturday, April 14, 2012

File Handling In Python III

Hello everyone, in this post we will discuss more about File Handling with Python..

Okay, so far I have discussed, how to create, append, read and close a File, also discussed about how to check the current directory and change directory, how to make new folder, etc.

In this post, lets start by showing you how to delete a folder and continue with few more functions.

Lets fire up the Python Shell..

>>> os.getcwd()
'C:\\Python27'
>>> os.chdir('C:\\files')
>>> os.listdir(os.curdir)
['i m siiting here.jpg', 'Looping with disctionary.txt', 'morefiles', 'Printout.docx', 'py1.html', 'Python post march20.txt', 'Python Post March21.txt', 'Python Post March22.txt', 'Python Post March25.txt', 'python post19th.txt', 'python.html', 'Python27march.txt', 'sub', 'test.html', 'test1.html', 'tkinter1.pdf', 'whiskey.html']
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sub
test.html
test1.html
tkinter1.pdf
whiskey.html
>>> # Now lets say I want to delete the test.html file
>>> os.remove('test.html') <--- Deletes a File
>>> Note: the parameter it takes is path, but since I am in the same directory, I just entered the file name, But If You want to Delete some thing on a different folder you need to type in the exact path, like C:\\folder\\subfolder\\file
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sub
test1.html
tkinter1.pdf
whiskey.html
>>> #test.html file is missing, means it has been deleted, now lets see how to rename a file, we will rename, we will rename test1.html to sample.html
>>> os.rename('test1.html', 'sample.html')
>>> for files in os.listdir(os.curdir):
             print files

   
i m siiting here.jpg
Looping with disctionary.txt
morefiles
Printout.docx
py1.html
Python post march20.txt
Python Post March21.txt
Python Post March22.txt
Python Post March25.txt
python post19th.txt
python.html
Python27march.txt
sample.html
sub
tkinter1.pdf
whiskey.html
>>>

We have another Function, that helps to walk through a directory, suppose u have a folder, where you have some files, and also few sub folders, where you have some more files. So os.walk() helps to recursively walk through the files. Lets check it out.

>>> path = 'C:\\files'
>>> for root, dirs, files in os.walk(path):
             print root
             print dirs
             print files
             print " "
           
C:\files
['morefiles', 'sub']
['i m siiting here.jpg', 'Looping with disctionary.txt', 'Printout.docx', 'py1.html', 'Python post march20.txt', 'Python Post March21.txt', 'Python Post March22.txt', 'Python Post March25.txt', 'python post19th.txt', 'python.html', 'Python27march.txt', 'sample.html', 'tkinter1.pdf', 'whiskey.html']

C:\files\morefiles
[]
['log.txt', 'myfile.txt', 'RHDSetup.log']
 
C:\files\sub
[]
['animated Pictures.txt', 'ASCII conversion Java.txt', 'average calculator 2 java.txt', 'back track wifi wpa hack.txt', 'backtrack.txt', 'backtrack2resolve.txt', 'bangladesh hackers friend.txt', 'bangladesh site hacked.txt', 'batch virus.txt', 'botnet.txt', 'CBT Sites.txt', 'CEH Linux commands.txt', 'CEHv7.txt', 'check how many times a character appears in word_java.txt', 'computer korner post.txt', 'constructor explained by Onty.txt', 'convertRHELtoCentos.txt', 'cpp keyloger.txt', 'crackinf for this software.txt', 'Cracking tut.txt', 'davemate2bhacked.txt', 'Deface and Shell.txt', 'defacepageCreator.txt', 'DummiesJava.txt', 'facebook emo added.txt', 'FootprintingCEH.txt', 'forum.txt', 'good site.txt', 'hack note.txt', 'hackers shell tool.txt']

 >>> #So what I asked Python is, please look for all the files in the folder named files under C: and display the path, display sub folders and then display the files.

 Yet Another Module, that I would like to present here, is the glob Module, that helps to display files matching a Pattern or regular expression. Lets check it out.

 >>> import glob
 >>> for files in glob.glob('C:\\files\\*.txt'):
             print files

   
C:\files\Looping with disctionary.txt
C:\files\Python post march20.txt
C:\files\Python Post March21.txt
C:\files\Python Post March22.txt
C:\files\Python Post March25.txt
C:\files\python post19th.txt
C:\files\Python27march.txt
>>> for files in glob.glob('C:\\files\\*.pdf'):
             print files

   
C:\files\tkinter1.pdf
>>> for files in glob.glob('C:\\files\\*.jpg'):
             print files

   
C:\files\i m siiting here.jpg
>>>

So you see that you can almost do anything and everything with Python, If you know Him well. Well I guess this was informative and Interesting and one of the important chapters in Python, So practice it well, and Don't Forget to check my next post.

Thank You.

Thursday, April 12, 2012

File Handling In Python II

Hello, everyone in this post, I will discuss the some more features of File Handling in Python, the very basics that you would need for handling and playing around with files in host operating system.

From the last post, we know how to create, append and read a text file in the root directory that is the C Drive of a Windows Operating system. Now what if we want to make a directory or probably create a text file somewhere else, but not in the C Drive.

So in this post, I will focus on how to jump around folders and directories.

For this we need to import a Module, named OS which is built into Python.

 >>> import os
>>> os.getcwd() <-- Returns the current working folder
'C:\\Python27'
>>> os.curdir <-- Returns the current working Drive or directory
'.'
>>> os.name <-- Returns the platform of a host Operating system.
'nt'
>>> os.mkdir('C:/PyProg') <-- Creates a New Folder
>>> os.mkdir('C:/PyProg/My_Project') <-- Creates a New Folder
>>> os.getcwd()
'C:\\Python27'
>>> os.chdir('C:/PyProg/My_Project') <--- Changes Directory
>>> os.getcwd() <-- Just a Proof, That The current Working Directory is different
'C:\\PyProg\\My_Project'
>>> os.environ <--- Returns the Environment Variables Of the Host OS.
[Try it out yourself, I am not showing the Output here, For some reason]
>>> os.listdir('C:/') <-- Directory Listing Of a Drive Or a Folder
['.rnd', 'ArrayDemo1.java', 'AUTOEXEC.BAT', 'boot.ini', 'Config.Msi', 'CONFIG.SYS', 'copy', 'dir1', 'Documents and Settings', 'files', 'Hacked.html', 'hacked.txt', 'Havij1.14Free.exe', 'Inetpub', 'Intel', 'IO.SYS', 'Java', 'log.txt', 'MSDOS.SYS', 'MSOCache', 'My Web Sites', 'NETCAT', 'NTDETECT.COM', 'ntldr', 'pagefile.sys', 'php', 'Program Files', 'pyinstaller', 'PyProg', 'Python27', 'pytoexe', 'RECYCLER', 'RHDSetup.log', 'ruby', 'streams.exe', 'System Volume Information', 'TC', 'Tc.exe', 'Tc.r00', 'Tc.r01', 'tests', 'themole-0.2.6', 'Visual Python', 'wamp', 'webgrabber', 'wget.exe', 'WINDOWS']
>>> os.getcwd()
'C:\\PyProg\\My_Project'
>>> myFile = open('Pythontext.txt', 'w')
>>> myFile.write(''' Hey, This are just the basics to show you how to use the OS Module with few examples.
If You want to Dive Deep into the Module.
Type, dir(os) in the Python Shell, To check the functions of the OS Module.
You can also type, help(os) to get a detailed report of the OS Module.
If you want to be specific about any function in the OS Module.
You need to type. help(os.function_name_of_any_OS_Module)''')
>>> myFile.close()
>>> os.getcwd()
'C:\\PyProg\\My_Project'
>>> os.listdir('C:/PyProg/My_Project')
['Pythontext.txt']
>>> myFile = open('Pythontext.txt')
>>> for lines in myFile:
                print lines

   
Hey, This are just the basics to show you how to use the OS Module with few examples.

If You want to Dive Deep into the Module.

Type, dir(os) in the Python Shell, To check the functions of the OS Module.

You can also type, help(os) to get a detailed report of the OS Module.

If you want to be specific about any function in the OS Module.

You need to type. help(os.function_name_of_any_OS_Module)
>>>
>>> myFile.close()

Well, These are the basic things that you would need very often, practice them, and Don't Forget to Check My next Post.

Thank You!

Wednesday, April 11, 2012

File Handling In Python

Hello Everyone, I guess This Post should be interesting as now we are in a position to go out of the Python Shell and touch the files of a host operating system.

In this post I will discuss about Handling File System. This is a Vast Topic where the inbuilt Python Module is not enough to get all our jobs done, but for starting point, and showing you how to use them, the inbuilt modules of Python works fine. The Word Module should not be unfamiliar with you in this post, and here onwards. And From here onwards I also assume that you know about Lists, tuples, Dictionary and all the stuffs that I posted Earlier.

Lets first start with how to create a file. So I am Going To show how to create a text file under the root directory of a Windows OS, i.e the C drive.

For a text file we should know, how to create, append, read and close a text file. We will work in the Python Shell, its same when you write a script in any text editor. Python interpreter would process and handle the scripts in same way.

The Basic Syntax for creating, appending, and reading is: variable_object_name = open('Relative Path', 'mode')

1. To create a text file named example.txt

>>> myFile = open('C:/example.txt', 'w') <--w means we want to write or create a text file
>>> myFile.write('This is the First Line\n')
>>> myFile.write('This is the second Line\n')
>>> myFile.writelines(''' This is blah blah blah......
....
...
....
This is the End of the Text file.\n''')
>>> myFile.close()

So first we have created a file in writing mode, and have written some lines, and finally closed the file.
write --> To write Lines in a text file line by line or as a paragraph
writelines --> To write a bunch of lines or paragraphs or to write a List we use writelines.

>>> sample = ['Python', 'Learning', 'is', 'Fun']
>>> myFile = open('C:/example.txt', 'a') <-- a means we want to append to the file
>>> myFile.writelines(sample)
>>> myFile.close()
>>>

2. To read the example.txt file

>>> myFile = open('C:/example.txt', 'r') <-- r means we want to read the file
>>> #By default, if we do not type the mode, python assumes it to be in read mode.
>>> myFile.read()
'This is the First Line\nThis is the second Line\n This is blah blah blah......\n....\n...\n....\nThis is the End of the Text file.\nPythonLearningisFun'
>>> myFile.seek(0)
>>> #seek(position) takes the python cursor to where-ever we want, since I will show some more read Functions, i have taken the cursor to the starting position.
>>> myFile.readline()
'This is the First Line\n'
>>> myFile.readline()
'This is the second Line\n'
>>> myFile.readline()
' This is blah blah blah......\n'
>>> myFile.readline()
'....\n'
>>> myFile.readline()
'...\n'
>>> myFile.readline()
'....\n'
>>> myFile.readline()
'This is the End of the Text file.\n'
>>> myFile.readline()
'PythonLearningisFun'
>>> myFile.readline()
''
>>> #readline --> reads line by line
>>> >>> myFile.seek(0)
>>> myFile.readlines()
['This is the First Line\n', 'This is the second Line\n', ' This is blah blah blah......\n', '....\n', '...\n', '....\n', 'This is the End of the Text file.\n', 'PythonLearningisFun']
>>> #readlines almost similar to read the difference is, it returns a List
>>> myFile.read()
'This is the First Line\nThis is the second Line\n This is blah blah blah......\n....\n...\n....\nThis is the End of the Text file.\nPythonLearningisFun'
>>> myFile.readlines()
[]
>>> myFile.seek(0)
>>> myFile.readlines()
['This is the First Line\n', 'This is the second Line\n', ' This is blah blah blah......\n', '....\n', '...\n', '....\n',
'This is the End of the Text file.\n', 'PythonLearningisFun']
>>> myFile.close()
>>>

To get a display in a readable manner, we use the For Iterator,

>>> myFile = open('C:/example.txt', 'r')
>>> for lines in myFile.readlines():
              print lines

   
This is the First Line

This is the second Line

 This is blah blah blah......

....

...

....

This is the End of the Text file.

PythonLearningisFun
>>> myFile.close()

Note: It is important to close a file, when you open it for any reason.

Now If You look in the C: Drive, you would see an example.txt file created.

Hope this was interesting, Practice it, play around with the functions, and Don't forget to check my next post.

Thank You.