Operation on files using Python

Share:
To do any operations on the files we need to open the file first. The open() method is used to returns the file object and it takes two arguments 

f = open("file_name",'mode')

methods to access files

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. To open the file for reading mode=" r ", opening the file for writing mode =  " w" 
when opened in writing mode if the file already exists then it will rewrite the content, to avoid this use mode = " a " this will add the content at the end of the file. The special mode 'rU' is the "Universal" option for text files where it's smart about converting different line-endings so they always come through as a simple '\n'. The mode is optional because when the mode is omitted " r " will be taken as the mode.

Methods for File objects
  • read()
To read file contents call  f.read(size) which reads size data and returns string in textmode and bytes object in binary mode.
  • readline()
It will read a single line from the file and a newline character (\n) is left at the end of the string but only for the last line, it will be not printed.
  • readlines()
If you want to read all the lines of a file in a list you can also use list(f) it will also gives you the same output.
  • write(string)
f.write(string) writes the contents of string to the file, returning the number of characters written.
To write any other types in your files you have to convert them into strings.

tuple = ( "PythonBlog", 13 )
a = str(tuple)
f.write(a)
  • tell()
tell function will return the position of the pointer where your object is pointed to the file
  • seek(offset, whence)
To change the object's position we use the seek method. To move x values forward take offset value as x.

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks.

with open("Pythonblog.txt") as f :
          read_data = f.read()

If with is not used make sure  f.close() is used in the program so that the file will be closed.

Python also uses JSON module to store the data.

write a program to print the longest word in the file?


No comments

F