DevOps | Cloud | Analytics | Open Source | Programming





Python Read and Write File (JSON, XML, CSV, Text) - Sample Code



Python Read and Write File (JSON, XML, CSV, Text) - Sample Code. In this post , we will see - How To Read & Write Various File Formats in Python.  

1. JSON Files - Read and Write from Python :

Write JSON Objects into Python :


\# Converting the JSON objects to print in Python
import json
\# some JSON: x =  '{ "city":"Washington", "population":300000, "country":"US"}'
\# parse x: y = json.loads(x)
\# the result is a Python dictionary: print(y\["city"\])

Converting Python Objects to JSON :


import json
\# Python Dictionary object: x = {
  "city":"Washington", 
  "population":300000, 
  "country":"US"
}

\# convert into JSON: y = json.dumps(x)

\# the result is a JSON string: print(y)

  Read JSON File :


import json

with open('<LOCATION/file.json') as f:
data = json.loads(f)

print(data)

# To Pretty Print
print(json.dumps(data, indent = 4, sort\_keys=True))

Write JSON Data to a File :


import json

data\_dict = {
  "city":"Washington", 
  "population":300000, 
  "country":"US"
}

with open('file.txt', 'w') as json\_file:
json.dump(data\_dict, json\_file)

 

2. XML Files - Read and Write from Python :

Consider an XML file with below sample contents - TEST.xml


<nodedetails>
  <name>SERVER-1</name>
  <description/>
  <numExecutors>SOME\_NO\_XX</numExecutors>
  <mode>SOME\_MODE\_XX</mode>
  <launcher class="xxxxx" plugin="xxxxx">
    <hostname>128.0.0.1</hostname>
    <portno>9900</portno>
    <credentialsId>TESTID</credentialsId>
    <maxNumRetries>3</maxNumRetries>
  </launcher>
  <label>somelabel</label>
</nodedetails>

Read from the XML File using ElementTree :


import xml.etree.ElementTree as ET
tree = ET.parse("TEST.xml")
root = tree.getroot()

for item in root.iter('nodedetails'):
    for name in item.iter("name"):
        print name.text
    for portno in item.iter("portno"):
        print portno.text

  Read from any XML File using Beautifulsoup :


from bs4 import BeautifulSoup

with open('ANYXMLFILE.xml', 'r') as f: 
data = f.read()

# Beautifulsoup will parse the data 
All\_data = BeautifulSoup(data, "xml")

# Finding all instances of any tag  
tag\_data = All\_data.find\_all('<ANY\_TAG\_NAME>')
print(tag\_data)

  Writing an XML File using ElementTree :


import xml.etree.ElementTree as ET

# Parent (root) tag 
data1 = ET.Element('parents')

# Adding a subtag named \`children\`  inside our root tag "parents"
data2 = ET.SubElement(data1, 'children')

# Adding subtags under the \`children\` subtag 
grandChild1 = ET.SubElement(data2, 'E4') 
grandChild2 = ET.SubElement(data2, 'D4')

# Adding attributes to the tags under 
# \`items\` 
grandChild1.set('card', 'Credit\_Card') 
grandChild2.set('card', 'Debit\_Card')

# Adding text to grandchildren subtags
grandChild1.text = "Only Credit Cards Accepted"
grandChild2.text = "Only Debit Cards Accepted"

# Convert xml data to byte object to write into filestream 
data\_xml = ET.tostring(data1)

# Write to a file with operation mode \`wb\` (write + binary) 
with open("OUTPUT.xml", "wb") as f: 
f.write(data\_xml)

  Writing to an XML using Beautifulsoup : (Assuming you are modifying the contents of an input XML file and Writing the modifying XML output to Another XML file)


#Open file
soup = BeautifulSoup(open('INPUT.xml'),'xml')

modified\_xml\_content = <MODIFIED XML content as per Business Logic>

#Write to a file
f = open('OUTPUT.xml', "w")
f.write(str(modified\_xml\_content))
f.close()

 

3. CSV Files - Read and Write from Python :

Read from CSV File using Native Python Lib :


import csv
with open('TESTFILE.csv') as inputfile:
data = csv.reader(inputfile, delimiter=',')

Read from CSV File using Pandas Lib :


import pandas as pd
data = pd.read\_csv('TESTFILE.csv')
# Display first 10 Lines of data
data.head(10)

Write to a CSV File using Native Python lib :


import csv

data = <DATA\_TO\_BE\_WRITTEN>

writer = csv.writer(open("OUTPUTFILE", 'w'))
for row in data:
   writer.writerow(row)

 


with open(filename, 'w', newline='') as testfile:
   wr = csv.writer(testfile, quoting=csv.QUOTE\_ALL)
   wr.writerow(list)

 

4. Text Files - Read and Write from Python :

Read from a Text File :


data = open ("<File\_Name>","Read\_Access\_Mode")

# OPEN THE FILE FOR READ ONLY
fileA = open("TESTFILE.txt","r")     
fileA.close() 

# Read data bytes in form of a string. If 'n" bytes not specified, it reads the entire file.
fileA.read(\[n\])

# Read a line of the file and returns in form of a string
fileA.readline(\[n\])

# Reads all the lines and return each line a string element in a list.
fileA.readlines()

  Write into the Text File :


\# OPEN THE FILE FOR READ & WRITE BOTH
fileB = open(r"TESTFILE.txt","w+") 

L = \["data line 1 \\n","data line 2 \\n","data line 3 \\n"\] 

fileB.writelines(L) 
fileB.close()

  Other Interesting Reads :

  python read and write to same file ,python read and write binary file ,python read and write file ,python read and write text file ,python read and write ,python read and write excel file ,python read and write csv file ,python read and write csv ,python read and write json file ,python read and write csv line by line ,python read and write to same file ,python read and write binary file ,python read and write file ,python read and write text file ,python read and write excel file ,python read and write csv file ,python read and write csv ,python read and write json file ,python read and write csv line by line ,python read and write a file at the same time ,python read and write xml ,python read and write xlsx ,python read and write xlsx file ,python read and write xls file ,python read and write xlsm ,python code to read and write xml file ,python read csv write xlsx ,python xlrd read and write