Skip to main content

Python Read and Write File

In this tutorial, you’ll learn how to read and write file in Python.

Program to Write to File

f = open("newtext.txt","w")
f.write("something to be write")
f.close()

Output:

this program will create a new file (if not exist) named as “newtext.txt” in the same directory where our program is located and write a line “something to be write”.

Program to Read File

f = open("newtext.txt","r")
print f.read()
f.close()

Output:

something to be write

As we have seen the program, it is very easy to read and write into a file in python. In python we can work with two type of files Text files and Binary files. In this tutorial we are working with text file.

Python Read and Write File

Let’s understand above programs.

f = open("newtext.txt", "w")

open() is just a function to get the file object. It gets the file object and returns it to the f, we can name f as we want. using file object’s methods and attributes we can access the information that file have.

open() takes two arguments, first the file name (in our case, its “newtext.txt”) and second one is for access mode (optional).

Access Modes: it is an attribute of file object. Which tells, in which mode the file is opened.

There are 4 types of access modes.

  1. r: r stands for reading mode. If we open our file in this mode then we can only read the file’s information.
  2. w: w stands for writing mode. If we open our file in this mode then we can only write into the file, can’t read. If the file is not already exist then it will create new one, if it exists then it will delete all the previous content from the file and start writing from starting of the file.
  3. a: a stands for appending mode. It is same as writing mode but the difference is it will not delete the previous content of the file. It starts writing from the last of the file. In other words, it will append (concatenate) the new content with previous one.
  4. r+: special read and write mode. If we open the file using this mode then we can both read and write into the file.

Note: access mode is optional in open() method. By default the file will open into read mode (r).

Come to the next line of our program.

f.write("something to be write")

write() is a method of file object to write into the file. We will write in the parenthesis, what we want to write into the file (as shown above).

To read from the file:

print f.read()

read() is a method of file object to read the information stored in a file object. read() method read all the information from the given file object and returns it.

Last line in our program:

f.close()

close() is a method of file object to close the opened file. Which means we can’t access the file in our program now.

There are many other useful methods of the file objects like:-

read(int): if we pass any digit to the read() method then it will return same number of characters from the file object.

Example:

Let’s say we have a text file named as “newtext.txt” and “the crazy programmer” have written into it.

f = open("newtext.txt", "r")
print f.read(9)
f.close()

Output:

the crazy

readline(): it is used to read a single line (separated by enter key or \n ) from the file object.

Example:

Lets say our text file is look like this:

line number 1
line number 2
line number 3

f = open("newtext.txt", "r")
print f.readline()
f.close()

Output:

line number 1

f = open("newtext.txt", "r")
print f.readline()
print f.readline()
f.close()

Output:

line number 1
line number 2

readlines(): it reads all lines in the file object and return it as a List of lines.

Example:

f = open("newtext.txt", "r")
print f.readlines()
f.close()

Output:

[ ‘line number 1\n’ , ‘line number 2\n’ , ‘line number 3\n’]

If we want to print a specific line then:

f = open("newtext.txt", "r")
lines = f.readlines()
#to print the 3rd line 
print lines[2]
f.close()

Output:

line number 3

seek(int): it sets the position of reading and writing pointer. Using seek() method we can navigate to start or last of the file object.

This method takes 0,1,2 as argument.

  • 0 – takes pointer to the starting
  • 1 – current position of the pointer
  • 2 – takes pointer to the end

Example:

f = open("newtext.txt", "r")
print f.readline()
print f.readline()
f.seek(0)
print f.readline()
f.close()

Output:

line number 1
line number 2
line number 1

We can also use with statement to open the files for better indentation.

#to write into the file
with open("file.txt","w") as f:
f.write("example line")

It will create a new file named as “file.txt” and write “example line” into it.

Comment below if you have queries regarding above python file handling tutorial.

The post Python Read and Write File appeared first on The Crazy Programmer.



from The Crazy Programmer https://www.thecrazyprogrammer.com/2018/01/python-read-write-file.html

Comments

Popular posts from this blog

Rail Fence Cipher Program in C and C++[Encryption & Decryption]

Here you will get rail fence cipher program in C and C++ for encryption and decryption. It is a kind of transposition cipher which is also known as zigzag cipher. Below is an example. Here Key = 3. For encryption we write the message diagonally in zigzag form in a matrix having total rows = key and total columns = message length. Then read the matrix row wise horizontally to get encrypted message. Rail Fence Cipher Program in C #include<stdio.h> #include<string.h> void encryptMsg(char msg[], int key){ int msgLen = strlen(msg), i, j, k = -1, row = 0, col = 0; char railMatrix[key][msgLen]; for(i = 0; i < key; ++i) for(j = 0; j < msgLen; ++j) railMatrix[i][j] = '\n'; for(i = 0; i < msgLen; ++i){ railMatrix[row][col++] = msg[i]; if(row == 0 || row == key-1) k= k * (-1); row = row + k; } printf("\nEncrypted Message: "); for(i = 0; i < key; ++i) f...

Data Encryption Standard (DES) Algorithm

Data Encryption Standard is a symmetric-key algorithm for the encrypting the data. It comes under block cipher algorithm which follows Feistel structure. Here is the block diagram of Data Encryption Standard. Fig1: DES Algorithm Block Diagram [Image Source: Cryptography and Network Security Principles and Practices 4 th Ed by William Stallings] Explanation for above diagram: Each character of plain text converted into binary format. Every time we take 64 bits from that and give as input to DES algorithm, then it processed through 16 rounds and then converted to cipher text. Initial Permutation: 64 bit plain text goes under initial permutation and then given to round 1. Since initial permutation step receiving 64 bits, it contains an 1×64 matrix which contains numbers from 1 to 64 but in shuffled order. After that, we arrange our original 64 bit text in the order mentioned in that matrix. [You can see the matrix in below code] After initial permutation, 64 bit text passed throug...

Accessibility Insights for the Web and Windows makes accessibility even easier

I recently stumbled upon https://accessibilityinsights.io . There's both a Chrome/ Edge extension and a Windows app, both designed to make it easier to find and fix accessibility issues in your websites and apps. The GitHub for the Accessibility Insights extension for the web is at https://github.com/Microsoft/accessibility-insights-web and they have three trains you can get on: Canary (released continuously) Insider (on feature completion) Production (after validation in Insider) It builds on top of the Deque Axe core engine with a really fresh UI. The "FastPass" found these issues with my podcast site in seconds - which kind of makes me feel bad, but at least I know what's wrong! However, the most impressive visualization in my opinion was the Tab Stop test! See below how it draws clear numbered line segments as you Tab from element. This is a brilliant way to understand exactly how someone without a mouse would move through your site. I can easily s...