带有示例的Python File readline()方法
文件readline()方法 (File readline() Method)
readline() method is an inbuilt method in Python, it is used to get one line from the file, the method is called with this object (current file stream/IO object) and returns one line from the file, we can also specify the total number of bytes to read from the line.
readline()方法是Python中的一種內(nèi)置方法,用于從文件中獲取一行,該方法與此對象(當(dāng)前文件流/ IO對象)一起調(diào)用,并從文件中返回一行,我們還可以指定從行讀取的總字節(jié)數(shù)。
Syntax:
句法:
file_object.readline(bytes)Parameter(s):
參數(shù):
bytes – It is an optional parameter and it can be used to specify the total number of bytes to read from the file. It's default value is -1 that specifies the whole line.
bytes –這是一個可選參數(shù),可用于指定要從文件讀取的總字節(jié)數(shù)。 它的默認(rèn)值為-1,用于指定整行。
Return value:
返回值:
The return type of this method is <class 'str'>, it returns the string.
該方法的返回類型為<class'str'> ,它返回字符串。
Example 1:
范例1:
# Python File readline() Method with Example# creating a file myfile1 = open("hello1.txt", "w")# writing content in the file myfile1.write("Shivang, 21, Indore\n") myfile1.write("Pankaj, 27, Mumbai\n") myfile1.write("Rambha, 16, Heaven\n")# closing the file myfile1.close()# reading the file (opening file in 'r' mode) myfile1 = open("hello1.txt","r")# reading and printing the file's content # line by line print("file's content (using readline() method)...") print("line1: ", myfile1.readline()) print("line2: ", myfile1.readline()) print("line3: ", myfile1.readline())# reading and printing the file's content # all at once using read() method# seeking the file position at 0th position myfile1.seek(0) print("file's content (using read() method)...") print(myfile1.read())# closing the file myfile1.close()Output
輸出量
file's content (using readline() method)... line1: Shivang, 21, Indoreline2: Pankaj, 27, Mumbailine3: Rambha, 16, Heavenfile's content (using read() method)... Shivang, 21, Indore Pankaj, 27, Mumbai Rambha, 16, HeavenExample 2:
范例2:
# Python File readline() Method with Example# creating a file myfile1 = open("hello1.txt", "w")# writing content in the file myfile1.write("Shivang, 21, Indore\n") myfile1.write("Pankaj, 27, Mumbai\n") myfile1.write("Rambha, 16, Heaven\n")# closing the file myfile1.close()# reading the file (opening file in 'r' mode) myfile1 = open("hello1.txt","r")# reading and printing the file's content # line by line print("file's content (using readline() method)...") # reads whole line print("line1: ", myfile1.readline(-1)) # reads 5 bytes print("line2: ", myfile1.readline(5)) # reads next 10 bytes print("line3: ", myfile1.readline(10))# closing the file myfile1.close()Output
輸出量
file's content (using readline() method)... line1: Shivang, 21, Indoreline2: Panka line3: j, 27, Mum翻譯自: https://www.includehelp.com/python/file-readline-method-with-example.aspx
總結(jié)
以上是生活随笔為你收集整理的带有示例的Python File readline()方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python程序查找表示O(1)复杂度的
- 下一篇: 数组重复次数最多的元素递归_使用递归计算