Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Data Analysis using Python/File 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("ashi.txt","a")#creating a text file f.write("Data Handling ")# writing to file f.write("\nwith python\n") f.close()
file=input("enter Name of file you want to open:") file=open(file,"r") #a=file.read() # reads whole file #b=file.read(10) # reads five letters c=file.readlines(3) # reads two lines #print(a) #print(b) print(c) file.close()
enter Name of file you want to open:ashi.txt ['Data \n']
with open("ashi.txt") 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("\nHI THis is pythonclasssss\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. pass lines=i+1 print("Number of lines in file:",lines)
Number of lines in file: 4

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(fname): import os statinfo = os.stat(fname) return statinfo.st_size print("File size in bytes of a plain file= ",file_size("python.txt"))
File size in bytes of a plain file: 53

Program to copy one file to another

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