File Operations in Python
How to open a file, read, print, write, append the contents.? All shown with the following example code and output
# Simple Excel file read
import pandas as pd
csv_file = pd.read_csv('csv.csv')
print(csv_file)
# # printed the following
# h1 h2 h3 h4
# 0 1 2 3 4
# 1 5 6 7 8
# 2 9 10 11 12
# 3 13 14 15 16
# ##################
#Excel file sheet1 reading specific
excel_file = pd.read_excel('sample.xlsx', sheet_name='Sheet1')
print(excel_file)
# Print out
# Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4
# read multiple sheets
df_sheet_multi = pd.read_excel('sample.xlsx', sheet_name=['Sheet1', 'Sheet2'])
print(df_sheet_multi)
#Printout
# {'Sheet1': Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4, 'Sheet2': Unnamed: 0 slno name age sal
# 0 1 11 11 11 11
# 1 2 22 33 44 55
# 2 3 66 66 66 66
# 3 4 77 77 77 77}
print(25*'-','Sheet1')
print(df_sheet_multi['Sheet1'])
# ------------------------- Sheet1
# Unnamed: 0 slno name age sal
# 0 1 1 1 1 1
# 1 2 2 2 2 2
# 2 3 3 3 3 3
# 3 4 4 4 4 4
print(25*'-','Sheet2')
print(df_sheet_multi['Sheet2'])
# ------------------------- Sheet2
# Unnamed: 0 slno name age sal
# 0 1 11 11 11 11
# 1 2 22 33 44 55
# 2 3 66 66 66 66
# 3 4 77 77 77 77
# To Create and write contents
f = open("demo.txt", "w")
f.write("I have written the contents!")
f.close()
#open and read the file after the appending:
f = open("demo.txt", "r")
print(f.read())
#prints => I have written the contents!
f.close()
f = open("demo.txt", "a")
f.write("Now I have written the contents more again !")
f.close()
#In demo.txt => I have written the contents!Now I have written the contents more again !
import os.path
file_exists = os.path.exists('readme.txt')
print(file_exists)
#False
import os.path
file_exists = os.path.exists('demo.txt')
print(file_exists)
#True
f = open("demo1.txt", "w")
f.write("I have written the contents!")
f.close()
f = open("demo2.txt", "w")
f.write(str(list(csv_file)))
f = open("demo2.txt","r")
print(f.read())
#f.close()
print(f.read())
#Print ['h1', 'h2', 'h3', 'h4']
Hope The above simple code snippets and printouts shown as comments is clear and understandable. Happy Open and Distance Learning!
No comments:
Post a Comment