python入门基础:文件的读写

文件的读写操作运用广泛,无论是何种语言都会涉及到文件的输入输出。

下面简单的总结一下文件的读写:

1:open()函数

f = open('workfile', 'w')

函数 open()返回文件的对象,通常的用法需要两个参数:open(filename, mode),

  • 其中filename 在初始都会自定义
 #手动规定文件的位置   下面为我演示的目录
file_abs ="G:\python\Notepad python\07:outputAndInput\f.txt"
  •  mode参数为自定义(下面列出一些常见的命令)

1.1:read()函数

f = open(file_abs,"r")
print(f.read())
f.close()

读取f文件的所有内容。

1.3:readline()函数

f.readline() 
#从文件中读取单独一行,字符串结尾会自动加上一个换行符(
print(f.readline())f.close()

1.4:循环遍历文件对象来读取文件中的每一行

for line in f:
    print(line,end='')

2:文件的写入   write()

#往文件里面写入一行,并且返回值,其中
表示换行符
print(f.write("This is a test in Notepad
"))

2.1:新创建文件并且写入

#手动规定文件的位置
file_abs ="G:\python\Notepad python\07:outputAndInput\write.txt"
    #手动向文件中写入
with open(file_abs,"w") as f:
    f.write("HelloWorld")

with open(file_abs, "r") as f:
    print(f.read())

    
    #重写f文件
with open(file_abs,"w") as f:
    f.write("HelloNewWorld")


    #在文件后面追加
with open(file_abs,"a") as f:
    f.write("fuck the world")    

3:关键字with的使用

#关键字 with 处理文件对象,推荐使用该方法
#优点在于:文件用完后会自动关闭,就算发生异常也没关系
    
with open(file_abs,"r+") as f :
    print(f.read())
    

 

原文地址:https://www.cnblogs.com/xiaxj/p/6951892.html