python 文件的内建函数

文件内建函数和方法

open()

打开文件

read()

读取

readline()

读取一行

seek()

文件内移动

write()

写入

close()

关闭文件

写入文件,此方法类似于unix中的>重定向写入,会覆盖源文件:

file1 = open("C:\\Users\\David\\Desktop\\a.txt",'w')
file1.write("abcdd")
file1.close()

读取文件的全部内容:

file1 = open("C:\\Users\\David\\Desktop\\a.txt")
print(file1.read())
file1.close()

在文件末尾追加写入,类似于unix中的>>:

file2 = open("C:\\Users\\David\\Desktop\\a.txt","a")
file2.write("\n")
file2.write("nnnnnnnnnnnnnnn")
file2.close()

读取文件中的第一行:

file1 = open("C:\\Users\\David\\Desktop\\a.txt")
print(file1.readline())
file1.close()

逐行读入,循环处理:

file1 = open("C:\\Users\\David\\Desktop\\a.txt")
for line in file1.readlines():
    if (line == "dsds
\n"):
        print(line)
file1.close()

指针在行上一个字符一个字符的向后读取:

file1 = open("C:\\Users\\David\\Desktop\\a.txt")
print(file1.tell())  
#打印读取行的行指
print(file1.read(1)) #读取第一个字符
print(file1.tell()) 
file1.close()

file2.seek(5,0) 

#第一个参数代表了偏移位置

#第二个参数 0表示从文件开头偏移;1表示从当前位置偏移;2表示从文件结尾偏移

猜你喜欢

转载自blog.csdn.net/David_ifx/article/details/104179961