Files
Files are named storage compartments on computers that are managed by the operating system.
Here mode can be typically the string ‘r’ to open for text input (the default), ‘w’ to create and open for
text output, or ‘a’ to open for appending text to the end.
Open a text file
fh = open(“hello.txt”, “r”)
Read a text file
fh = open(“hello.txt”,”r”)
print (fh.read())
Read one line at a time
fh = open(“hello”.txt”, “r”)
print (fh.readline())
Read a list of lines
fh = open(“hello.txt.”, “r”)
print (fh.readlines())
Write to a file
fh = open(“hello.txt”,”w”)
write(“Hello World”)
fh.close()
Write a list of lines to a file
fh = open(“hello.txt”, “w”)
lines_of_text = [“a line of text”, “another line of text”, “a third
line”]
fh.writelines(lines_of_text)
fh.close()
Append to a file
fh = open(“Hello.txt”, “a”)
write(“Hello World again”)
fh.close()
Close a file
fh = open(“hello.txt”, “r”)
print fh.read()
fh.close()
Sample Program (to read a file)
f = open(“test.txt”,’r’) # open file in current directory
print (f.read(5))
print(‘\n’)
print (f.read(8))
print (f.readlines(1))
print (f.readlines())
Output:
this
is first
[‘ file for python\n’]
[‘this is the second line\n’, ‘this is the third line of first python file’]
Sample Program (to write a file)
file = open(‘test.txt’, ‘w’)
file.write(‘This is a first script’)
file.write(‘To add more lines in a file.’)
file.close()
Filing Practice Codes
Q1. The cryptography function crypto takes as input a string (i.e., the name of a file in the current directory). The function should print the file on the screen with this modification: Every occurrence of string ‘secret’ in the file should be replaced with string ‘xxxxxx’.
def crypto(a): f=open('crypto.txt','r+') f=f.read().replace('secret','xxxxxx') return print(f) a=input('file name extension included; ') crypto(a)
Q2. The function censor takes the name of a file (a string) as input. The function should open the file, read it, and then write it into file censored.txt with this modification: Every occurrence of a four-letter word in the file should be replaced with string ‘xxxx’. Note that this function produces no output, but it does create file censored.txt in the current folder.
def censor(a): f=open(a,'r') g=f.read() h=g.split() w= input('enter the file name to be created with extension') p=open(w,'w') for word in h: if len(word) >= 4: q=word[:5] q='xxxx' r=q+word[5:]+'' else: r=word+'' p.write(r) print(p) a=input('enter file name') censor(a)
Q3. Write a function fcopy that takes as input two file names (as strings) and copies the content of the first file into the second line by line.
def fcopy(): a = input('Enter name of original file with extension : ') b = input('Enter name of file to be created with extension : ') f=open(a) x=open(b,'w') c=f.read().split() for line in c: y=x.write(line+'\n') print() fcopy()
Q4. Implement function distribution that takes as input the name of a file (as a string). This one-line file will contain letter grades separated by blanks. Your function should print the distribution of grades.
def distribution(a): b=open(a) c=b.read().split() count0 =0 count1 = 0 count2 = 0 count3 = 0 count4 = 0 count5 = 0 count6 = 0 count7 = 0 for i in c: if i == 'A+': count0 += 1 elif i == 'A': count1 += 1 elif i == 'B': count2 += 1 elif i == 'B+': count3 += 1 elif i == 'B-': count4 += 1 elif i == 'C': count5 += 1 elif i == 'C-': count6 += 1 elif i == 'F': count7 += 1 print(count0,' students got A+') print(count1,' students got A') print(count2,' students got B+') print(count3,' students got B') print(count4,' students got B-') print(count5, ' students got C') print(count6, ' students got C-') print(count7, ' students got F') a = input('Enter name of file with extension : ') distribution(a)
Q5. Develop a program to read a file in a remote directory with for loop.
f= open('Filename/path',r) for i in f: print(i, end=" ") print(f.close())
Q6. Develop a script that prints the words of file separated by commas.
with open(<file_name>) as f: text =f.read() text = text_split("") print (text)
Q7. Develop a script to find the longest word in the file.
length = str() with open(file-name>) as f: text = f.read() text = text.split() for i in text: if len(i)>len(length): length=i print ("Longest word is", length)