Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python Basics/File Handling-Day4.ipynb
3074 views
Kernel: Python 3
## Time Module: from time import time, ctime t = time() ctime(t)## for current time
import time current_local = time.localtime() current_local.tm_zone
import time a=time.strftime('%m-%y-%d', time.localtime()) t = time.strftime("%d/%m/%y|%H:%M:%S") print (a) print(t)
09-20-16 16/09/20|13:47:30
print(time.strftime("%y/%m/%d|%H:%M:%S"))
20/09/16|13:53:22
Tstr=time.strftime("%A/%B|%a/%b") # Day|MONTH print(Tstr) tstr=time.strftime("%H:%M:%p")# Current time IN AM/PM print(tstr) w=time.strftime("%z") print(w)
Wednesday/September|Wed/Sep 13:57:PM +0530
530
import datetime print("Current date and time: " , datetime.datetime.now()) print("Current year: ", datetime.date.today().strftime("%Y")) print("Month of year: ", datetime.date.today().strftime("%B"))#%b print("Week number of the year: ", datetime.date.today().strftime("%W")) print("Weekday of the week: ", datetime.date.today().strftime("%w")) print("Day of year: ", datetime.date.today().strftime("%j")) print("Day of the month : ", datetime.date.today().strftime("%d")) print("Day of week: ", datetime.date.today().strftime("%A"))
Current date and time: 2020-09-16 13:50:32.358677 Current year: 2020 Month of year: September Week number of the year: 37 Weekday of the week: 3 Day of year: 260 Day of the month : 16 Day of week: Wednesday
from time import strftime, localtime print(strftime('%c', localtime())) time.sleep(10) print(strftime('%c', localtime()))
Wed Sep 16 13:54:37 2020 Wed Sep 16 13:54:47 2020
import calendar #prints Calendar of specified month c = calendar.month(2020,2) print(c) print("Calendar of year") print (calendar.TextCalendar(calendar.MONDAY).formatyear(2017, 2, 2, 2, 2))
#Leap Year Check a=int(input("Input year to enter")) leap=calendar.isleap(a) print(leap)

File Handling

File handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on file. image.png

Key Words: open(), "w","r","a","read(5)",readlines()

  • open(): "r": read(oPENING, ERROR IF FILE IS NOT THERE)

    "a": append- (open file, create a file if it does not exits and append) "w" : write-(open file, create a file if does not exits and write)
  • "t": Text: Default value(Text mode)

  • "b": Binary: Binary mode(Images)

f = open(r"C:\Users\suyashi144893\Documents\data Sets\Mobilevariants.txt","r") print(f)
<_io.TextIOWrapper name='C:\\Users\\suyashi144893\\Documents\\data Sets\\Mobilevariants.txt' mode='r' encoding='cp1252'>
f=open("Dat.txt","a")# f.write("\npython") f.close()
f=open("Dat.txt","r")#creating a text file a=f.read() print(a) f.close()
pythonpython python
a=input("enter Name of file you want to open:") file=open(a) #file=open("‪Quiz.txt","r") #a=file.read() # reads whole file b=file.read(10) # reads 10 letters c=file.readlines() # reads two lines #print(a) #print(b)‪ print(a) file.close()
enter Name of file you want to open:dat.txt dat.txt
with open("Demo.txt","r") as f: data = f.read() print(data)
HI THis is python classsss Welcomeall study
## We can also split lines using file handling in Python. #This splits the variable when space is encountered. with open("Demo.txt", "r") as file: data = file.readlines() for line in data: word = line.split() print (word )
['HI'] ['THis', 'is', 'python'] ['classsss'] ['Welcomeall'] ['study']

Ques: Program to count number of lines in a file

with open("ashi.txt" ,"w") as f: f.write("Python is an interpreted\n, high-level, \ngeneral-purpose programming language. \nCreated by Guido van Rossum and first released in 1991, Python's design \nphilosophy emphasizes \ncodereadability with its notable use of significant whitespace") #Program to count no. of lines: with open("ashi.txt") as file: for i,l in enumerate(file):#Enumerate means look line by line. print(i,l) lines=i+1 print("Number of lines in file:",lines)

Ques: Program to find largest word in a file

#Program to print largest word in file: with open("ashi.txt") as file: words=file.read().split() print(words) max_len=len(max(words,key=len)) for word in words: if len(word)==max_len: print("The longest word in file = %s and its length = %d :"%(word,max_len))

To get the file size of a plain file

def file_size(file): import os statinfo = os.stat(file) return statinfo.st_size print("File size in bytes of a plain file = ",file_size("Demo.txt"),"bytes")
File size in bytes of a plain file = 48 bytes

To copy one file to another

from shutil import copyfile copyfile('ashi.txt', 'ab1.txt') print("ashi.txt is copy created")