Data Handling and Data Connection in Python

In this blog, I would be talking about

  • how to open file
  • how to close the file
  • how to create a file
  • how to read a file
  • how to write in a file
  • context management

What is FILE?

A file is a container in a computer system for storing information. Files used in computers are similar in features to that of paper documents used in library and office files. There are different types of files such as text files, data files, directory files, binary and graphic files, and these different types of files store different types of information. In a computer operating system, files can be stored on optical drives, hard drives, or other types of storage devices.

Python gives you easy ways to manipulate these files. Generally, we divide files into two categories, text file, and binary file. Text files are simple text whereas binary files contain binary data that is only readable by the computer.

How to open a file?

Python has a built-in function to open files. The open() helps us in opening files in Python. This function returns a file object, also known as a handle It is used to read or manipulate the file accordingly.

SYNATX : open(filename, mode)
where
argument1 is the filename, name of the file to be opened or create
argument2 is mode ; it specifies the purpose of opening a file such as for reading or writing
Examplesfile1=open("MyCode.txt",'r' # It return string contain of the file

In Python, reading is assumed to be the default mode. In this mode, we get strings when reading from the file.

On the other hand, the binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files.

How to close the file?

In any language, it is assumed to be the best practice to close a file once your file work is done. However, Python runs a garbage collector to clean up the unused objects. But you must do it on your own instead leave it for the GC. Python has a close() method which closes an opened file. It has no effect if the file is already closed.

file2=open("MyCode.txt",'r')
#do the file operation
file2.close()

How to create a file?

If it's Python, each time you will have an easy way to get through it. Here’s some way to create a new file in Python. Along with open() use ‘x’, ‘w’ or ‘a’ as argument2. For mode ‘x’, it creates the file else it returns an error and the other two modes will create a file if the specified file does not exist.

file3 = open("Mycode.txt", "x")
file4 = open("myCode.txt", "w")
file5 = open("Code.txt", "x")

How to read a file?

To read any file in Python we do need to open it before reading it in ‘r’ mode. By default, read() reads the whole file. However, to read a specific element, we need to give size i.e. read(size). It will read the content up to that specific size.

file6 =open("Mytext.txt",'r')
print(file6.read())

There are methods like readline() which reads and returns one line from the file, readlines() which reads and returns a list of lines from the file.

How to write in a file?

To write in a file, we need to open the file in ‘x’, ‘w’, or ‘a’ mode. Python has write() to write in a file. However one should much take care while writing in a file in ‘w’ mode. It overwrites onto the files if the opened already exist. This, in turn, refreshes the file will new content.

file7=open("MyText.txt",'w')
file7.write("Code Eat Sleep")
##this will overwrite the content of Mytext.txt file and as result of which now it will return Code Eat Sleep.

Python has many file methods. Built-in methods like seek(), tell(), flush(), detach(), etc. For more give it a read.

Context management

Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with statement.

with open('Code_file', 'w') as file8:
file8.write('Hello Everyone!!')

The “with” statement in Python is regarded as an obscure feature by some. But when you peek behind the scenes of the underlying Context Manager protocol you’ll see there’s little “magic” involved. Opening files using the with statement is generally recommended because it ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement.

It helps simplify some common resource management patterns by abstracting their functionality and allowing them to be factored out and reused.

In turn, this helps you write more expressive code and makes it easier to avoid resource leaks in your programs.

file8 = open('Code_file', 'w')
try:
file8.write('Hello Everyone!!')
finally:
file8.close()

While comparing it to the first example we can see that a lot of code is eliminated just by using with. The main advantage of using a with statement is that it makes sure our file is closed without paying attention to how the nested block exits.

Python Database Connection

As most software applications need to interact with data in some form, programming languages like Python provide tools for storing and accessing these data sources.

What is a database?

A database is an organized collection of data, generally stored and accessed electronically from a computer system. Where databases are more complex they are often developed using formal design and modeling techniques.

Two types of databases are :

a. SQL databases

b. NoSQL databases

SQL Databases

A database in SQL Server is made up of a collection of tables that stores a specific set of structured data. A table contains a collection of rows, also referred to as records or tuples, and columns, also referred to as attributes. Each column in the table is designed to store a certain type of information, for example, dates, names, dollar amounts, and numbers.

There are various products developed for SQL like MySQL, PostgreSQL, Oracle etc.

NoSQL Databases

NoSQL stands for Not Only SQL, most people think it stands for no SQL, but it’s not.It is a Non-Relational database which means as relational database they do not use tables and columns .It is a flexible database used for big data and real time web applications.We have multiple types of NoSQL databases like Document database,Graph database,Key-value Stores and so on.

There are four major types of NoSQL databases emerged: document databases, key-value databases, wide-column stores, and graph databases

Thank you for giving your valuable time :)

References

https://www.mongodb.com/nosql-explained

https://www.mongodb.com/nosql-explained/nosql-vs-sql

https://www.mongodb.com/blog/post/getting-started-with-python-and-mongodb

https://docs.python.org/3/library/io.html#io.StringIO

https://docs.python.org/3/library/filesys.html

3rd year CSE student at IIITKALYANI , enthusiastic learner and explorer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store