File Handling in Python python ocean

 

 

 

 

Python also supports file handling and allows users to read and write files, along with many other file handling options. The concept of file handling is spread across various other languages, but its implementation is either complex or lengthy, but like other python concepts, the concept here is simple and concise. Python treats the file as text or binary and this is important. Each line of code contains a sequence of letters and they create a text file. Each line of the file is terminated with a special character, called EOL or End of line characters such as comma {,} or new line character. This ends the current line and tells the interpreter that a new line has begun. Let's start with reading and writing files.

 

Working of open() function


We use the Open () function in Python to open a file in read or write mode. As described above, open () will return a file object. To return a file object, we use the open () function with two arguments, which accepts the name and mode of the file, whether read or write. So, the syntax is: open (file name, mode). There are four types of modes that Python provides and how to open files:

                1. “ r “, for reading.

                2. “ w “, for writing.

                3. “ a “, for appending.

                4. “ r+ “, for both reading and writing

 

 

Creating and Writing File python ocean


Below code will create file with name first_file.txt and write the given content to file in write() method , first argument is name of file and "w" argument is given for writing purpose.

file = open("first_file.txt","w")
file.write("My first file")
file.write("\nAnother Random line")
file.close()

 

 

Reading File


To read file, again we can use open() function but this time, "r" will be used to read, there are several ways to read file, either using .read() or using .readlines()

read() will get content from file with out any changes

readlines() will return python list of all lines in file.

for loop can be used to print content of file (reading lines one by one)

All methods examples are given below

 

file = open("first_file.txt","r")
print(file.readlines())

 

file = open("first_file.txt","r")
print(file.read())

 

file = open('first_file.txt', 'r')
for everything in file:
    print (everything)

 

 

Appending Data to existing file


Below code will append line "this is new data" to existing data in first_file.txt

file = open("first_file.txt","a")
file.write('\n This is the new data')
file.close()

 

 

pythonocean filhandling file handling python ocean Python ocean ocean graphy python ocean

Python Ocean python ocean python 3 sklearn keras machine learning tensorflow opencv

usman.vecho usman.vecho@gmail.com