python3 文件的读取和通用操作

来源:互联网 发布:知乎 长青春痘 编辑:程序博客网 时间:2024/05/22 13:40


import os           # 当前操作目录,os.chdir() 切换操作目录

>>> import os

>>> os.getcwd()

'C:\\ProgramFiles\\Python36'

 

open(“路径”,“模式“,encoding= “编码”)

          (1.)路径

             1.  ”c:\\path\\data.txt”

             2.  r”c:\path\data.txt”

             3.  “data.txt”

            (2)  模式

             1. 文本

              “r”    #  只读

              “w”    #   写

              “rw”    #   读写

               “r+”    #  读写

                “w+”   #  先创建新文件,再读

              “a”    #  增加

2. 二进制

“*b”  # 二进制的读取

 

通用操作

  读取

num= (open("names.txt","r",encoding="utf-8").read())#打开文件,并读取

"r""w"文件的读取不能同时操作

num = (open("names.txt","w",encoding= "utf-8"))num.write("中国\n美国")# python默认’w’写入文件,会替换掉原有文档
   # 如果是在原文件上进行内容的追加,使用"a"(append的意思)

num= (open("names.txt","a",encoding="utf-8"))
num.write("中国\n日本")

 
num = (open("names.txt","r",encoding= "utf-8"))num1 = (num.readline())  # 读取文件的一行# 读取多行用for循环for i in range(5)读取文件5行    print(num.readline())
#  注意区别  readline(),readlines()是循环文件

# readlines(),是加载整个文件,所以只适合读小文件

forindex,i in enumerate(num.readlines())读取到第5行提示
   
if index ==5:
       
print("__到第五行啦__")
        continue
   
print(index,i,end="")  

# 大小文件通吃的方法就是一行内存只保存一行数据

num= (open("names.txt","r",encoding="utf-8"))
count = 0
for i in num:
    if
count == 5:
      
print("----到第五行啦----")
       count +=1
      
continue
   
print(i,end="")
    count += 1

 
 

 

.read()   #一次性读取所有文本

           f =open(r"e:\python\demo\course.txt","r")

            >>>f.read()

'fengsenwangxueyatom'

 

.read(n)   # n代表读取指定的字符

>>>f.read(2)

'fe'

>>>f.read(6)   #  指针并没有到末尾,可以接着读取

'ngsenw'

 

.readlines()    #  读取行到列表

>>>a = f.readlines()

>>>a

['fengsenwang\n','xueyatom']

 

>>>f.seek(0)

0

 

     

fengsenwang

xueyatom

 

 

 

# .encoding  文件的字符编码

print(num.encoding)  #  打印文件的字符编码

 

 

num= (open("names.txt","r", encoding="utf-8"))
print(num.tell())  # 查看指针所在的位置

 

 

.seek(n)  # 指针归零

    >>>f.read   #  再次提取,提示错误,需要把提取指针归零

<built-inmethod read of _io.TextIOWrapper object at 0x00000193D8CA51F8>

    >>>f.seek(0)   # 提取指针归零

0

>>>f.read()

'fengsenwangxueyatom'

    >>>print(f.read())     # 文件打印换行

fengsenwang

xueyatom

.close()  # 关闭文件链接

    >>>f.close()         #  关闭读取文件

   

    写入

1.    write() 写入字符串

    >>> scores =open("youpintest.txt","w",encoding= "utf-8")   # 写入文件的参数

>>> scores.write("机构:威科姆公司\n网址:www.yjt361.com") #写入文件的内容

26      # 写入文件的字符的数量

    >>>scores.close()  #确认写入完毕,否则文件打开没有内容

2.    .flush() 不关闭文件情况下输出缓存到磁盘

    >>>people_names = ['tom','jerry','mike','peter']

>>>m = open("names.txt",'w',encoding='utf-8')

>>>m.writelines(people_names)

    >>> m.flush()  # 强制刷新到磁盘

 

 

 

# 类似进度条的功能

importsys,time
for i in range(20):
   
sys.stdout.write("*")
    sys.stdout.flush() # 及时刷新 和print()有区别
    time.sleep(0.2)   

# 文件内容的替换,不覆盖,新增

num= (open("names.txt","r", encoding="utf-8")) # 被替换的文档
num_new = (open("nemes_new","w",encoding="utf-8")) # 新建文档
for i in num:   # 循环num 内容
  if "中国"in
i: # 寻找便跟内容
   
i =i.replace("中国","88888") # 替换
  num_new.write(i)  # 替换内容写进文档
num.close()
num_new.close()

 

 

 

   # 给原列表每个字符后面添加 \n

    >>>n = [name+"\n" for name in people_names]

>>>n    # 给原列表每个字符后面添加 \n

['tom\n','jerry\n', 'mike\n', 'peter\n']

>>>t = open('names.txt','w',encoding='utf8')

>>>t.writelines(n)   # python默认’w’写入文件,会替换掉原有文档

# 追加文件的内容,

>>>e = ['fengsen','wangxueya']

>>>t = open('names.txt','a',encoding='utf-8')

>>>t.writelines(e)  #不删除原有的内容,写入的时候用’a’

>>>t.flush()

>>>t.close       # 养成好习惯,结束写入,关闭文件

      # 默认关闭文件的格式

>>>with open("names.txt",'r',encoding='utf-8')as t:

      for line in t:

             print(t)

>>>with open("names.txt",'r',encoding='utf-8')as t:

      for line in t:

             print(line)

 

            

tom

 

jerry

 

mike

 

peter

 

fengsenwangxueya

>>>with open('names.txt','w',encoding='utf8')as t:

      t.write('hello\n')

      t.write('world\n')

把列表放入在文件中

考虑一下list里含有数字:,用str()函数转一下,看你要处理的数据了

>>>l=["A","B","C","D"]

>>>f=open("k.txt","w")

>>>f.write(str(l))

>>>f.close()

>>> 

这样的输出就是一个list  ["A","B","C","D"]

 

原创粉丝点击