Skip to main content

Python File Handling

Python File Handling

All programs need the input to process and output to display data. And everything needs a file as name storage compartments on computers that are managed by OS. Though variables provide us a way to store data while the program runs, but if we want out data to persist even after the termination of program, we have to save it to a file.

File and its path

There are always two parts of a file in computer system, the filename and its extension. Also the files have two key properties – its name and the location or path, which specifies the location where the file exists. The file name has two parts and they are separated by a dot (.) or period.
Figure – File and its path:
Directory Structure
A built-in open method is used to create a Python file-object, which provides a connection to the file that is residing on programmer’s machine. After calling the function open, programmers can transfer strings of data to and from the external file that is residing in the machine.

File Opening In Python

open() function is used to open a file in Python. It’s mainly required two arguments, first the file name and then file opening mode.
Syntax:
file_object = open(filename [,mode] [,buffering])
In the above syntax the parameters used are:
  • filename: It is the name of the file.
  • mode: It tells the program in which mode the file has to be open.
  • buffering: Here, if the value is set to zero (0), no buffering will occur while accessing a file, if the value is set to top one (1), line buffering will be performed while accessing a file.

Modes Of Opening File In Python

The file can be opened in the following modes:
Python File Opening Modes
ModeDescription
rOpens a file for reading only. (It’s a default mode.)
wOpens a file for writing. (If file doesn’t exist already, then it’s creates a new file, otherwise it’s truncate a file.)
xOpens a file for exclusive creation. (Operation fails if file does not exists in location.)
aOpens a file for appending at the end of the file without truncating it. (Creates a new file if it does not exist in location.)
tOpens a file in text mode. (It’s a default mode.)
bOpens a file in binary mode.
+Opens a file for updating (reading and writing.)

File Object Attributes

If an attempt to open a file fails then open returns a false value, otherwise it returns a file object that provides various information related to that file.
Example:
#!/usr/bin/python

# file opening example in Python
fo
= open("sample.txt", "wb")
print "File Name: ", fo.name
print "Mode of Opening: ", fo.mode
print "Is Closed: ", fo.closed
print "Softspace flag : ", fo.softspace
Output:
File Name: sample.txt
Mode of Opening: wb
Is Closed: False
Softspace flag: 0

File Reading In Python

For reading and writing text data different text-encoding schemes are used such as ASCII (American Standard Code for Information Interchange), UTF-8 (Unicode Transformation Format), UTF-16.
Once a file is opened using open() method then it can be read by a method called read().
Example:
#!/usr/bin/python

# read the entire file as one string
with open('filename.txt') as f:
data
= f.read()

# Iterate over the lines of the File
with open('filename.txt') as f:
for line in f :
print(line, end=' ')
# process the lines

File Writing In Python

Similarly for writing data to files, we have to use open() with ‘wt‘ mode, clearing and overwriting the previous content. Also we have to use write() function to write into a file.
Example:
#!/usr/bin/python

# Write text data to a file
with open('filename.txt' , 'wt') as f:
f
.write ('hi there, this is a first line of file.\n')
f
.write ('and another line.\n')
Output:
hi there, this is a first line of file.
and another line.
By default, in Python – using the system default text encoding files are read/written. Though Python can understand several hundred text-encodings but the most common encoding techniques used are ASCII, Latin-1, UTF-8, UTF-16 etc. The use of ‘with’ statement in the example establishes a context in which the file will be used. As the control leaves the ‘with’ block, the file gets closed automatically.

Writing A File That Does Not Exists

The problem can be easily solved by using another mode – technique i.e. the ‘x‘ mode to open a file instead of ‘w‘ mode.
Let’s see two examples to differentiate among them.
Example:
#!/usr/bin/python

with open('filename' , 'wt') as f:
f
.write ('Hello, This is sample content.\n')

# This will create an error that the file 'filename' doesn't exist.

with open ('filename.txt' , 'xt') as f:
f
.write ('Hello, This is sample content.\n')
In binary mode, we should use ‘xb‘ instead of ‘xt‘.

Closing A File In Python

In Python, it is not system critical to close all your files after using them, because file will auto close after Python code finishes execution. You can close a file by using close() method.
Syntax:
file_object.close();
Example:

#!/usr/bin/python

try:
# Open a file
fo
= open("sample.txt", "wb")
# perform file operations
finally:
# Close opened file
fo
.close()



Comments

For Programs Click Here

Popular posts from this blog

Syllabus

Syllabus  C Programming Tutorials C Tutorial C Introduction History of C Programming Language C Installation C Program Structure C Input and Output (I/O) C Format Specifiers Declaration & Assignments C Tokens C Identifiers C Keywords C Constants C Operators C Data Types C Variables C Preprocessors C Type Casting C Custom Header File Flow Control C Decision Making C if Statements C if-else Statements C Nested if-else Statements C else-if Statements C goto Statement C switch Statements C Loops C while loops C do while loops C for loops Functions C Functions C Function Arguments C Library Functions C Variable Scope Arrays & Strings C Arrays C Strings Pointers C Pointers C Dynamic Memory Allocation Structure & Union C Structures C Unions File I/O C File Handling C fopen C fclose C getc C putc C getw C putw C fprintf C fscanf C fgets C fputs C feof                                                                 Other C99 Features C Error Handling

Python Overview

Python Overview Python is a general purpose object-oriented programming language with high-level programming capabilities. It has become famous because of its clear and easily understandable syntax, portability and easy to learn. Some Facts About Python Python was developed in the late eighties i.e. late 1980’s by  Guido van Rossum  at the  National Research Institute for Mathematics and Computer Science  in the Netherlands as a successor of ABC language capable of exception handling and interfacing. Python is derived from programming languages such as: ABC, Modula 3, small talk, algol-68. PHP page is a file with  .py  extension that contains could be the combination of HTML Tags and Python scripts. In December 1989 the creator developed the 1st python interpreter as a  hobby  and then in 16 October 2000, Python 2.0 was released with many new features. On 3rd December 2008,  Python 3.0  was released with more testing and includes new features. Python is an open source scripting languag

C++ Tokens

Declaration & Assignments C++ Tokens As mentioned earlier, C++ is the superset of  C  and so most constructs of C are legal in C++ with their meaning and usage unchanged. So tokens, expressions and data types are similar like that of C. It also is preferred to understand the concepts of C before learning C++. However there are some exceptions and additions in C++ which you will not get in C. In this chapter you will learn about what are tokens, and the different types of tokens, expressions, and basic data types. What are Tokens Each individual word and punctuation is referred to as a token in C++. Tokens are the smallest building block or smallest unit of a C++ program. These following tokens are available in C++: Identifiers Keywords Constants Operators Strings Identifiers : Identifiers are names given to different entries such as variables, structures and functions. Also identifier names should have to be unique because these entities are used in the execution of the program. Ke