Python Tutorials - Simple way to open file and write/read data


python file logo


      In python programming language you can handle and do a lot of things with files.
read, write data and close file by certain functions and simple codes.
      The first thing you need to do is open the file, you can do it with the function open()
It takes 3 arguments :
open (name [, mode [, buffering]])   
           1 - In the first argument you write the file name
and don’t forget .txt 
           2 - In the second argument you write model (there is
a lot of models but we will use just see some models that we need in this tutorial)
           3 -The last argument buffering is optional
        The first line in our code looks like this:
        
   We are creating a new variable with the name “file” and we call in it a function to open a file and create it
First argument – “test.txt” – we give a name for our file and in second argument we choose ‘W’ model it is mean “Write”, we write ‘w’ in the second argument when we need to write something in the file.
          Now it's time to write some data in our file:
        
         We called the function write() to write some text in our file
 \n between text, it is mean jump to the new line and in our text file it  will appear like this:
tuto
python
tutorial
python tutorials
           Before we finish, we need to close the file by this function:
          
In Desktop you will see the file created with all data that you wrote


code to open and write data in files
         Now we want to read file data to do what we need with it
   First thing, open the file
        
         We wrote our file name and “r” model it is for read data that is inside  files..
To read just one line in the file
You need to call this function readline()
       

but if you want to read and show all the lines, you call this function read()
       

code to open and read data in files

        you can show the data in a list  by readlines function.. Look at this example here:
        

code to open and read data in files
             after we finish reading data we have to close file

         
                    
                        We hope you understand this python tutorial... For more information about file functions… visit the official python documentation.



Latest
First