Python Fundamentals and Advanced

ksshravan
2 min readJun 23, 2024

--

This article covers the following topics

  • File Handling

File Handling (based on University of Michigan Coursera course)

  • Flat text files : Flat file is a simple data file without a structured interrelationship among its records, typically stored in a plain text format
  • To read a file use open(), this return a handle used to manipulate the file
handle = open(filename, mode)

# use "r" as mode to read a file
# use "w" as mode to write to a file
  • Handle is an interface to interact with the file. In more detail, it is a data structure that keeps track of the open file. One important thing that is tracked is the file position. The position/pointer is set in POSIX by the lseek() function and is read by the tell() function. Any read() or write() takes place from position of current file pointer
  • If you try to open a file which does not exist, you get FileNotFound error
  • Newline character is a special character which indicates when a file ends, represented using \n (note that it is considered as a single character although it has 2 characters in it)
sentence = "Hello\nWorld"
print(sentence)
#Output:
#Hello
#World
print(len(sentence)) # Output: 11
  • If you have 2 back to back newline i.e \n\n you get a blank line
  • When print encounters \n, it does not print it, instead it goes to next line and starts printing the net character from there. Moreover print statement adds a \n at the end of every statement by default (this can be changed by using the end argument in print)
print("Hello")
print("World")
# Hello
# World

print("Hello", end='')
print("World")
# HelloWorld
  • File handle can be treated as a sequence of strings, where each line in the file is a string in the sequence
xfile = open('quotes.txt')
count = 0
for line in xfile:
print(line)
count = count + 1

print("Line count : ", count)
  • To read the entire file at once, we can use the read() function
fhand = open("quote.txt")
inp = fhand.read() # contains entire file as a single string
print(len(inp))
  • To close a file,we use the close() function. A better approach is to use the with keyword while opening the file, as it ensure that file handle is automatically closed
  • We can also mention file encoding while reading file (very important many times)

--

--