Thursday, December 22, 2011

Python File Operations

Alright ,it is time for python file operation related examples. there could be a variety of things that you would like to do with a file. I am sharing a simple example below.

old_file= open ("file_Path","r")
new_file = open ("file_Path","w")

for line in old_file:
if "" in line:
new_file.write(line.replace("oldtext","newtext"))
else:
new_file.write(line)

In the above example we are opening a file in read and write mode and performing some basic operations.

Based on a condition we are trying to replace some content in the file and writing the new thing in a different file.

this code works as is , you just have to give the appropriate values. sys is the only module you will be needing.

No comments:

Post a Comment