File and string handling in Python

Every programming language should have the facility of file handling. At least basic open, close, read, and write file records.

To access the file we have two options in python. One obviously to give the whole path in every file operations and another and the best one should be set your path of the files and access the files by only names.

import os

os.chdir(“F:\Praxis\Somenath\Python”)

This will create the current path of as the path given in the CHDIR parameter.

Basic syntax of open and read files

f = open(“months.txt”)   <- open the file and assign file pointer to “f” and months.txt is saved in the above path.

print(f.read())                                   <- read all the records from months.txt and print the same in console.

file1

But if we want to read the file by number of records we need to pass the parameters in read function like below

f.read(1)                              <- will read 1 character from the file from the current position of the file pointer.

file2

If you pass 2 instead of 1 it will read 2 characters per execution of the read function.

If you want to read files by the line we need to execute below command

f.readlines() <- here also we can pass the parameter for the number of lines you want to read per execution of readlines function. By default it is one line per execution.

file3

Open operation open the file by default in “read” mode, if you want to open the file to write (in write mode), we need to specifically mention it in the command like below

fout = open(“test_ex_out.txt”, “w“) ß open test_ex_out.txt file in write mode and assign file pointer to fout.

Then to write records we need to execute below “write” command

fout.write(“First line”) ß this will write “First line” in fout (test_ex_out.txt) file.

String Operations:

After reading from files or any user input we always need string functions to manipulate strings as per our need.

Strip:

It will remove extra spaces and extra lines from the string.

Syntax :

STRING.strip()

Split

This will split strings based on the parameter passed.

Syntax :

line.split(” – “)

Leave a Comment

Scroll to Top