Open In App

Saving Text, JSON, and CSV to a File in Python

Last Updated : 29 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats.

Opening a text file in Python

Opening a file refers to getting the file ready either for reading or for writing. This can be done using the open() function.

Syntax:

File_object = open("File_Name", "Access_Mode")

Parameters:

  • File_Name: The name of the file that is needed to be opened.
  • Access_Mode: Access modes govern the type of operations possible in the opened file.

Following are the most commonly used access modes:

  • Read Only (‘r’): Open text file for reading.
  • Write Only (‘w’): Open the file for writing.
  • Append Only (‘a’): Open the file for writing. The data being written will be inserted at the end, after the existing data.
  • Read and Write (‘r+’): Open the file for reading and writing.

Note: By default, Python assumes the access mode as read i.e (“r”)




# Python program to demonstrate 
# opening a file 
    
    
# Open function to open the file "myfile.txt"   
# (same directory) in read mode and store 
# it's reference in the variable file1 
    
file1 = open("myfile.txt"
    
# Reading from file 
print(file1.read()) 
    
file1.close() 


Note: For more information, refer to Open a File in Python.

Saving a Text File in Python

After learning about opening a File in Python, let’s see the ways to save it. Opening a new file in write mode will create a file and after closing the file, the files get saved automatically. However, we can also write some text to the file. Python provides two methods for the same.

  • write(): Inserts the string str1 in a single line in the text file.
    File_object.write(str1)
  • writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.
    File_object.writelines(L) for L = [str1, str2, str3] 

Example:




# Python program to demonstrate
# saving a text file
  
  
file = open('read.txt', 'w')
file.write('Welcome to Geeks for Geeks')
file.close()


Output:

saving-text-file-python

With Statement

with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources.

Syntax:

with open filename as file:
     statement(s)

Example:




# Python program to demonstrate
# saving a text file
  
  
with open('read.txt', 'w') as file:
      
    books = ['Welcome\n'
             'Geeks\n'
             'to\n'
             'Geeks\n',
             'for\n'
             'Geeks\n'
             'world\n']
      
    file.writelines("% s\n" % data for data in books)


Output:

saving-text-file-python

Note: For more information, refer to Writing to file in Python.

Saving a CSV File in Python

CSV is a Comma Separated Values files are most widely utilized for putting tabular data. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. Python has built-in module called csv to write and Save a CSV File.

To save a CSV File:

  • First, we need to import csv library.
  • Then open the file as we usually do but instead of writing content on the read_file object, we create a new object called read_writer.
  • This object provides us with the writelines() method which allows us to place all the row’s data within the enter one go.

Example:




# Python program to demonstrate 
# writing to CSV 
    
    
import csv  
      
# field names  
fields = ['Name', 'Branch', 'Year', 'CGPA']  
      
# data rows of csv file  
rows = [ ['Nikhil', 'COE', '2', '9.0'],  
         ['Sanchit', 'COE', '2', '9.1'],  
         ['Aditya', 'IT', '2', '9.3'],  
         ['Sagar', 'SE', '1', '9.5'],  
         ['Prateek', 'MCE', '3', '7.8'],  
         ['Sahil', 'EP', '2', '9.1']]  
      
# name of csv file  
filename = "university_records.csv"
      
# writing to csv file  
with open(filename, 'w') as csvfile:  
    # creating a csv writer object  
    csvwriter = csv.writer(csvfile)  
          
    # writing the fields  
    csvwriter.writerow(fields)  
          
    # writing the data rows  
    csvwriter.writerows(rows)


Output:

python-save-csv

Note: For more information, refer to Writing CSV files in Python.

Saving a JSON File in Python

The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. The text in JSON is done through quoted-string which contains the value in key-value mapping within { }.

This module provides a method called dump() which converts the Python objects into appropriate json objects.




import json 
    
# python object(dictionary) to be dumped 
dict1 =
    "emp1": { 
        "name": "Lisa"
        "designation": "programmer"
        "age": "34"
        "salary": "54000"
    }, 
    "emp2": { 
        "name": "Elis"
        "designation": "Trainee"
        "age": "24"
        "salary": "40000"
    }, 
    
# the json file where the output must be stored 
out_file = open("myfile.json", "w"
    
json.dump(dict1, out_file, indent = 6
    
out_file.close() 


Output:

save-json-python

Note: For more information, refer to Working With JSON Data in Python.



Previous Article
Next Article

Similar Reads

Saving scraped items to JSON and CSV file using Scrapy
In this article, we will see how to use crawling with Scrapy, and, Exporting data to JSON and CSV format. We will scrape data from a webpage, using a Scrapy spider, and export the same to two different file formats. Here we will extract from the link http://quotes.toscrape.com/tag/friendship/. This website is provided by the makers of Scrapy, for l
5 min read
Scrape IMDB movie rating and details using Python and saving the details of top movies to .csv file
We can scrape the IMDb movie ratings and their details with the help of the BeautifulSoup library of Python. Modules Needed: Below is the list of modules required to scrape from IMDB. requests: Requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests must be learne
4 min read
Saving API Result Into JSON File in Python
As Python continues to be a prominent language for web development and data processing, working with APIs and storing the obtained data in a structured format like JSON is a common requirement. In this article, we will see how we can save the API result into a JSON file in Python. Saving API Result into JSON File in PythonBelow is the step-by-step
3 min read
Saving a Pandas Dataframe as a CSV
In this article, we will learn how we can export a Pandas DataFrame to a CSV file by using the Pandas to_csv() method. By default, the to csv() method exports DataFrame to a CSV file with row index as the first column and comma as the delimiter. Creating DataFrame to Export Pandas DataFrame to CSV C/C++ Code # importing pandas as pd import pandas a
2 min read
How to Remove Index Column While Saving CSV in Pandas
In this article, we'll discuss how to avoid pandas creating an index in a saved CSV file. Pandas is a library in Python where one can work with data. While working with Pandas, you may need to save a DataFrame to a CSV file. The Pandas library includes an index column in the output CSV file by default. Further in the article, we'll understand the d
3 min read
PyCairo - Saving SVG Image file to PNG file
In this article, we will see how we can save an SVG file to a PNG file using PyCairo in Python. We can create an SVG file using SVGSurface method. An SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files ar
2 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Python Script to Monitor Network Connection and saving into Log File
In this article, we are going to see how to monitor the network connection and save the log file in Python. The basic ideology of this script is to give real-time information about if the system the script is being run on is connected to an internet connection or not, and save that information into a log file simultaneously, keeping records of when
8 min read
Convert Text File to CSV using Python Pandas
Let's see how to Convert Text File to CSV using Python Pandas. Python will read data from a text file and will create a dataframe with rows equal to number of lines present in the text file and columns equal to the number of fields present in a single line. See below example for better understanding. Dataframe created from upper text file will look
2 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
three90RightbarBannerImg