Files - Exercises
https://www.w3resource.com/python-exercises/file/
1. Find the longest word in a file.
open a file for reading. You can do this several ways.
If the file is small, the best way would be
- read all the contents into a variable
- split it using split()
- use max with key=len (Syntax is key=func()) to obtain the longest word
- print it.
#fname = input("Enter a file name:")
fname = "mbox-sample.txt"
try:
fhand=open(fname)
except:
print("File cannot be opened:",fname)
exit()
#longest word
contents = fhand.read()
words = contents.split()
l_word = max(words, key=len)
print(l_word)
Output:
<postmaster@collab.sakaiproject.org>
2. Write a Python program to get the file size of a plain file
This is required in many cases where you might want to check the file size before accepting an upload.
2 methods you can use belong to the os package
- os.stat() - https://docs.python.org/3/library/stat.html
- os.path.getSize() https://docs.python.org/3/library/os.path.html?highlight=getsize#os.path.getsize
#file size of plain file
import os
fname = "mbox-sample.txt"
statinfo = os.stat(fname)
print(statinfo.st_size)
3.Write a Python program to read last n lines of a file
2 other useful methods in a file handle are readLines() and readLine()
readlines() reads all the lines in a file as a list
readline() - reads a line, you can specify an argument as to how many bytes to read also.
to read last n lines, read all the lines into a list
use slicing to read the last to lines from the last [-2:]
n=2
fhand=open(fname)
#read last n lines
for line in fhand.readlines()[-n:]:
line = line.rstrip();
print(line)
4. Write a Python program to read first n lines of a file
just do the opposite
or set up a count variable and break when it is equal to n
n=2
fhand=open(fname)
#read first n lines
count=1
for line in fhand:
if count>n: break
line = line.rstrip();
print(line)
count+=1
5. Write a Python program to append text to a file and display the text
Open file to write in 'a' append mode
remember to close the file before trying to read from it again.
Always close file when you write to it.
#append to a file
fhand = open('jrr.txt')
print("Initial contents of file:")
print(fhand.read())
fout = open('jrr.txt','a')
line="Not all who wander are lost"
fout.write(line)
fout.close()
fhand = open('jrr.txt')
print("After Appending:")
print(fhand.read())
Output:
Initial contents of file:
Not all that glitters is gold
After Appending:
Not all that glitters is gold
Not all who wander are lost
6. Write a Python program to copy the contents of a file to another file
use the copyfile method of the shutil class.
import shutil
shutil.copyfile('jrr.txt','jrr2.txt')
fhand= open('jrr2.txt')
print("contents of jrr2.txt")
print(fhand.read())
7. Write a Python program to read a random line from a file.
This is a good exercise to try as we had studied random package.
choice method of random will return a random choice from a sequence.
split('\n') is equivalent to splitlines() - use any one
this returns a list which is a sequence.
#read random line from file
import random
fhand=open('mbox-short.txt')
num_lines = fhand.read().split("\n")
print(random.choice(num_lines))
Output:
Received: from nakamura.uits.iupui.edu (localhost [127.0.0.1])
8. Write a Python program to assess if a file is closed or not
closed is a boolean value that you can use to obtain the state of a file handle.
#assess if a file is closed or not
fhand = open('mbox.txt')
print(fhand.closed)
fhand.close()
print(fhand.closed)
9. Write a Python program to remove newline characters from a file
use the method we had learnt or read everything at once, split using '\n' and join again.
#strip new line characters
fhand= open('mbox-sample.txt')
text=''
for line in fhand:
line=line.rstrip()
text+=line
print(text)
1. Find the longest word in a file.
open a file for reading. You can do this several ways.
If the file is small, the best way would be
- read all the contents into a variable
- split it using split()
- use max with key=len (Syntax is key=func()) to obtain the longest word
- print it.
#fname = input("Enter a file name:")
fname = "mbox-sample.txt"
try:
fhand=open(fname)
except:
print("File cannot be opened:",fname)
exit()
#longest word
contents = fhand.read()
words = contents.split()
l_word = max(words, key=len)
print(l_word)
Output:
<postmaster@collab.sakaiproject.org>
2. Write a Python program to get the file size of a plain file
This is required in many cases where you might want to check the file size before accepting an upload.
2 methods you can use belong to the os package
- os.stat() - https://docs.python.org/3/library/stat.html
- os.path.getSize() https://docs.python.org/3/library/os.path.html?highlight=getsize#os.path.getsize
#file size of plain file
import os
fname = "mbox-sample.txt"
statinfo = os.stat(fname)
print(statinfo.st_size)
3.Write a Python program to read last n lines of a file
2 other useful methods in a file handle are readLines() and readLine()
readlines() reads all the lines in a file as a list
readline() - reads a line, you can specify an argument as to how many bytes to read also.
to read last n lines, read all the lines into a list
use slicing to read the last to lines from the last [-2:]
n=2
fhand=open(fname)
#read last n lines
for line in fhand.readlines()[-n:]:
line = line.rstrip();
print(line)
4. Write a Python program to read first n lines of a file
just do the opposite
or set up a count variable and break when it is equal to n
n=2
fhand=open(fname)
#read first n lines
count=1
for line in fhand:
if count>n: break
line = line.rstrip();
print(line)
count+=1
5. Write a Python program to append text to a file and display the text
Open file to write in 'a' append mode
remember to close the file before trying to read from it again.
Always close file when you write to it.
#append to a file
fhand = open('jrr.txt')
print("Initial contents of file:")
print(fhand.read())
fout = open('jrr.txt','a')
line="Not all who wander are lost"
fout.write(line)
fout.close()
fhand = open('jrr.txt')
print("After Appending:")
print(fhand.read())
Output:
Initial contents of file:
Not all that glitters is gold
After Appending:
Not all that glitters is gold
Not all who wander are lost
6. Write a Python program to copy the contents of a file to another file
use the copyfile method of the shutil class.
import shutil
shutil.copyfile('jrr.txt','jrr2.txt')
fhand= open('jrr2.txt')
print("contents of jrr2.txt")
print(fhand.read())
7. Write a Python program to read a random line from a file.
This is a good exercise to try as we had studied random package.
choice method of random will return a random choice from a sequence.
split('\n') is equivalent to splitlines() - use any one
this returns a list which is a sequence.
#read random line from file
import random
fhand=open('mbox-short.txt')
num_lines = fhand.read().split("\n")
print(random.choice(num_lines))
Output:
Received: from nakamura.uits.iupui.edu (localhost [127.0.0.1])
8. Write a Python program to assess if a file is closed or not
closed is a boolean value that you can use to obtain the state of a file handle.
#assess if a file is closed or not
fhand = open('mbox.txt')
print(fhand.closed)
fhand.close()
print(fhand.closed)
9. Write a Python program to remove newline characters from a file
use the method we had learnt or read everything at once, split using '\n' and join again.
#strip new line characters
fhand= open('mbox-sample.txt')
text=''
for line in fhand:
line=line.rstrip()
text+=line
print(text)
Comments
Post a Comment