
Since we need the file for reading, we are going to make use of read mode i.e. The wb mode will open the file for writing binary data. The rb mode will open the file for binary data reading. Using a with open() will open the file in write mode, and the contents will be appended at the end. The mode argument is a string.įollowing are the modes available that can be used with open() method: Mode The two important arguments that goes in open() function are the file path, which is a string, and the mode that specifies whether the file is meant for reading or writing. The basic file IO in Python to open a file for reading or writing is the built-in open() function. Save the file demo.txt and use the location of the demo.txt inside open() function. We are going to make use of demo.txt file used earlier. The first line will be fetched, and it will return the line with characters from 0 to 10. The given example has the size parameter given as 10. You can also make use of the size parameter to get only the required length of the line.
#Python file write line how to#
We have seen how to read the entire line from the file given. Once the reading is done, close the file using close() method as shown below:Įxample: Using size argument in readline() Let us now print the line to see the details: Use the readline() method to read the line from the file demo.txt as shown below: Right now, we have used “r”, which means the file will open in read mode. The open() method takes the first parameter as the name of the file, and the second parameter is the mode is while you want to open. The following are the steps to read a line from the file demo.txt.įirst, open the file using the file open() method, as shown below: The file contents of demo.txt are as follows: We are going to make use of demo.txt file here to read the contents. Here will understand how to read the line from the file given using the readline() method. Example: To read the first line using readline() The readline() method returns the line from the file given. By default, the value of size is -1, and hence the entire string is returned. Size: (optional) Here, you can specify the number, an integer value to readline(). By default, the size is 0, and it returns the entire line.

Example: Using size argument in readline().Example: To read the first line using readline().
