13.python文件操作

1.读取整个文件
首先要创建一个文件

with open('file_name.type') as  file_object:#在文件所在的目录中查找文件
    for line in file_object:
        print(line)

2.文件路径
文件夹text_files位于文件夹python_work中,可使用相对文件路相径来打开该文件夹中的文件
文件的绝对路径,是值文件在计算机中的准确位置

file_path='text_files/filename.txt'
with open(file_path) as  file_object:

3.逐行读取

file_path='text_files/filename.txt'
with open(file_path) as  file_object:
  for line in file_object:
     print(line)

4.写入文件

filename ='programing.txt'
with open(filename,'w') as file_object:#可指定读取模式 读 ('r' )、写入模式 写 ('w' )、附加模式 附 ('a' )或让你能够读取和写入文件的模式('r+' )。
    file_object.write("1234")
   
 file_object.write("8910")

写入文件时需要注意是否是让每个字符串单独占一行,如果需要,在write()语句中包含换行符,不然都会一行显示
如果想要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件,即不会在返回对象文件前清空文件,而是写入的行都将添加到文件末尾,

filename ='programing.txt'
with open(filename,'a')
    file_object.write("1234")
   
 file_object.write("8910")

5.使用文件中的内容

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容