- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reading and Writing Files in Python
The file object provides a set of access methods to make our lives easier. We would see how to use read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings can have binary data and not just text.
The write() method does not add a newline character ('
') to the end of the string −
Here, passed parameter is the content to be written into the opened file.
#!/usr/bin/python # Open a file fo = open("foo.txt", "wb") fo.write( "Python is a great language.
Yeah its great!!
") # Close opend file fo.close()
The above method would create foo.txt file and would write given content in that file and finally it would close that file. If you would open this file, it would have following content.
Python is a great language. Yeah its great!!
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings can have binary data. apart from text data.
Here, passed parameter is the number of bytes to be read from the opened file. This method starts reading from the beginning of the file and if count is missing, then it tries to read as much as possible, maybe until the end of file.
Let's take a file foo.txt, which we created above.
#!/usr/bin/python # Open a file fo = open("foo.txt", "r+") str = fo.read(10); print "Read String is : ", str # Close opend file fo.close()
This produces the following result −
Read String is : Python is
- Reading and Writing Files in Perl
- Reading and Writing to text files in Python
- Reading and Writing to text files in Python Program
- Reading and Writing to text files in C#
- Reading and writing Excel files using the openpyxl module in Python
- Reading and Writing CSV File using Python
- Reading and writing binary file in C/C++
- Writing files in background in Python
- What are reading and writing characters in C language?
- Writing files in the background in Python
- Reading/Writing a MS Word file in PHP
- How to open an Excel file with PHPExcel for both reading and writing?
- Reading images using Python?
- Reading Keyboard Input in Python
- Opening and Closing Files in Python