Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python core/Day 3File Handling.ipynb
3074 views
Kernel: Python 3

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

f=open("i.txt","a")#creating a text file f.write("Machine Learning ")# writing to file f.write("\n Interne of things") f.close()
file=input("enter Name of file you want to open:") #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:ashi.txt
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-13-f06ddbf16757> in <module>() 2 file=input("enter Name of file you want to open:") 3 #file=open("‪Quiz.txt","r") ----> 4 a=file.read() # reads whole file 5 #b=file.read(10) # reads five letters 6 #c=file.readlines(3) # reads two lines AttributeError: 'str' object has no attribute 'read'
with open("ashi.txt","r") as file: data = file.read() print(data)
Data with python Data Handling with python
## We can also split lines using file handling in Python. #This splits the variable when space is encountered. with open("python.txt", "r") as file: data = file.readlines() for line in data: word = line.split() print (word )
['Learn', 'Data', 'Science'] ['with', 'python'] [] ['Data', 'Visualization']

Ques: Program to count number of lines in a file

with open("ashi.txt" ,"w") as f: f.write("HI \nTHis is python\nclasssss\nWelcomeall\nstudy") #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)
0 HI 1 THis is python 2 classsss 3 Welcomeall 4 study Number of lines in file: 5

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))
['HI', 'THis', 'is', 'pythonclasssss', 'Welcomeall', 'study'] The longest word in file = pythonclasssss and its length = 14 :

Ques : A Python program 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("ashi.txt"))
File size in bytes of a plain file= 48

Program to copy one file to another

from shutil import copyfile copyfile('ashi.txt', 'abc.txt')
'abc.txt'