Python file handling

Python file handling allows us to working on files . In python file handling is simple and easy task. We can perform various operations on files in python like open , read etc.

What is file handling?

A file represents a sequence of related data (objects), stored as sequence of bytes on disk. It is used for permanent storage. File handling is a process of working on that files. We can say file handling is a process of handle, manage files which are stored  on permanent memory of system. It includes opening , reading, writing and closing files.

Python file handling

Python allows us to working on files . In python file handling is simple and easy task. We can perform various operations on files in python like open , read, write change files etc. Python also treated as text file and binary file differently i.e.:

Text file

Sequence of characters forms a word, and sequence of words forms a text file.

Binary file

A binary file contains sequence of bytes. There is byte code in whole file. Example: Image file.

Python file handling Operations

In python, we can perform various operations on files.  Some basic operations are:

  1. Opening file ( open() )
  2. Reading file( read() )
  3. Writing file( write() )
  4. Closing file( close() )
  5. Renaming file ( rename() )
  6. Deleting file ( remove() )
  7. Spliting file elements ( split() )

Let’s discuss these methods in brief:

Open a file

In python,  we use open() function to open a file, we can open a file for various purposes, i.e to read, write, add data etc.It returns the file object.  The syntax for opening file is as below:It

Syntax

open("filename.extension",'mode','closed?')

Attributes of file

  • File-name: It is the string value of name of file which is going to open. After filename, dot and extension of file follows file-name.
  • Mode: The second attribute is the mode of file, in which file goes to open . It’s default value is ‘read’. It means if we does not specify any mode, and try to write file, then there will be an error (because it uses default mode only read) .
  • Closed: It is the third attribute of file, it checks whether a file is close or not. It returns a boolean value, true if file closed otherwise false.

Modes of file

There are various modes of file, with which we can open a file. There are two types of modes in which we can open file, these are:

  1. Text Mode : for text file, which contains only text
  2. Binary Mode : for byte code file, which may contains images , or other special type data(not text)

There is an table for all modes of python files:

Sr No.

Mode

Description

1

r

Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

2

rb

It opens in Reading mode for binary format. It is the default mode. Pointer is at beginning of file.

3

r+

It opens a file in both, reading and writing mode. The pointer points the beginning element of file.

4

rb+

It opens a file in both read and write mode for binary format. There also pointer points the first element (beginning).

5

w

It opens a file in writing only in text format. If there exists the file with same name, it overwrites the content, otherwise create a new file for writing only.

6

w+

It opens a file in both reading and writing in text format. If there exists the file with same name, it overwrites the content, otherwise create a new file for writing and reading.

7

wb

It opens a file in binary format for writing only.If there exists file with same name , it will overwrite the content, otherwise will create a new file for writing only.

8

wb+

It opens a file in binary format for both reading and writing. If the file exists, it will overwrite the file content, otherwise create a new file for both reading and writing.

9

a

It opens a file in append mode i.e pointer of file points the last location of content. If there exists a file, then it will add (append) content in existing file, otherwise create a new file for appending.

10

a+

It opens a file in both append and read mode i.e pointer of file points the last location of content. If there exists a file, then it will add (append) content in existing file, otherwise create a new file for appending and reading.

11

ab

It opens a file in append mode in binary format, i.e pointer of file points the last location of content. If there exists a file, then it will add (append) content in existing file, otherwise create a new file for appending.

12

ab+

It opens a file in both read and append mode in binary format, i.e pointer of file points the last location of content. If there exists a file, then it will add (append) content in existing file, otherwise create a new file for appending and reading in binary format.

Writing to a file

To write contents on file, we first need to open file, and then we use write() method. To write content on file there are two methods:

  • append (a) – Add text to the end of file.
  • write(w) – Overwrite existing content.

which i have already explained in table above. The syntax for writing to file is given below:

Syntax

filename.write("Content")

Example

python file handling
python file handling

As you can see in the image above, i have write on file.py, before executing program, there was not a file file1.py in my system.  After executing above code, it make new file file.py and writes the given content on that. If you try to write some other content on the same file, you will see, the new content will overwrite the previous one.

append (‘a’)

As we discuss earlier, append mode will adds new content in previous one, unlike  ‘w’ which overwrites the previous one.

Example

python file handling
python file handling

Asyou can see in example above, new content appended to the previous one.

Creating a file

Mode ‘x’ is used to create a file it returns error if the file already exists unlike “w”.

python file handling
python file handling

‘w’ vs ‘x’ (Difference between write and create)

write(“w”) will create a new file if the file does not exists, and overwrite previous content if file already exist.

In other hand, create (“x”) returns an error if the file with the same name already exists.

Now we have discussed opening , writing , creating files, and access modes of files. We will discuss about further methods in our further article, you can visit link below. Thanks.

Python read file

 

 

143 thoughts on “Python file handling

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Pretty section of content. I just stumbled upon your blog and in accession capital to assert that I get in fact enjoyed account your blog posts. Any way I will be subscribing to your augment and even I achievement you access consistently rapidly.

  2. I am not sure where you are getting your information, but great topic. I needs to spend some time learning more or understanding more. Thanks for wonderful information I was looking for this information for my mission.

  3. After study a handful of the blog posts on the web site now, and that i genuinely like your method of blogging. I bookmarked it to my bookmark site list and you will be checking back soon. Pls check out my web-site also and inform me if you agree.

  4. certainly like your website but you need to check the spelling on quite a few of your posts. A number of them are rife with spelling problems and I find it very bothersome to tell the truth nevertheless I will definitely come back again.

  5. I have been browsing online more than 3 hours as of late, yet I by no means discovered any attention-grabbing article like yours. It¡¦s pretty value enough for me. Personally, if all web owners and bloggers made just right content as you probably did, the net will likely be a lot more helpful than ever before.

  6. Undeniably believe that which you stated. Your favorite justification seemed to be on the web the simplest thing to be aware of. I say to you, I definitely get irked while people consider worries that they just do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  7. You actually make it seem so easy with your presentation but I find this matter to be really something that I think I would never understand. It seems too complicated and extremely broad for me. I am looking forward for your next post, I’ll try to get the hang of it!

  8. Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a little bit, but instead of that, this is fantastic blog. A fantastic read. I will definitely be back.

  9. Good blog! I truly love how it is simple on my eyes and the data are well written. I am wondering how I could be notified whenever a new post has been made. I’ve subscribed to your RSS feed which must do the trick! Have a great day!

  10. I precisely had to thank you very much once again. I am not sure the things I would’ve tried in the absence of the type of solutions discussed by you about this situation. Certainly was a real frightening concern for me personally, but encountering this expert approach you processed the issue forced me to leap with gladness. Now i am happier for your information and in addition have high hopes you recognize what a powerful job you are carrying out teaching the rest thru your webblog. I’m certain you have never got to know all of us.

  11. I just want to tell you that I am newbie to blogging and definitely savored you’re web site. Probably I’m want to bookmark your blog post . You really come with terrific posts. Thanks a bunch for sharing your blog site.

  12. When I originally commented I clicked the -Notify me when new surveys are added- checkbox and from now on every time a comment is added I purchase four emails using the same comment. Could there be by any means you are able to get rid of me from that service? Thanks!

  13. Can I recently say what a relief to discover somebody that actually knows what theyre dealing with on the net. You certainly understand how to bring a difficulty to light to make it important. Workout . need to check this out and understand this side from the story. I cant think youre no more common when you certainly possess the gift.

  14. Hello, i think that i saw you visited my website so i came
    to “return the favor”.I am attempting to find things to improve my
    site!I suppose its ok to use a few of your ideas!!

  15. What’s Happening i am new to this, I stumbled upon this I have found It absolutely helpful and it has aided me out loads.
    I am hoping to contribute & assist other users like its aided me.
    Great job.

  16. It’s appropriate time to make a few plans for the future and it is time to be happy.
    I have learn this put up and if I may just I desire to recommend you some interesting things or
    advice. Maybe you can write subsequent articles relating to this article.
    I want to learn even more issues about it!

  17. Thanks pertaining to spreading this particular wonderful individuals that you really know what you’re communicating roughly! Saved. Generously furthermore consult with the internet site Equates to). We shall possess a web page link industry understanding involving people Thanks pertaining to spreading this particular wonderful individuals that you really know what you’re communicating roughly! Saved. Generously furthermore consult with the internet site Equates to). We shall possess a web page link industry understanding involving people

  18. Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

  19. “Nice post. I learn something new and challenging on blogs I stumbleupon on a daily basis. It’s always helpful to read articles from other authors and use something from their web sites.”

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.