python写文件以及全局变量int类型的使用注意

参考链接

Python for循环写入文件--小结-dsy851009-ChinaUnix博客

二进制文件的读写-python3_尘埃落定-CSDN博客_python3 读取二进制文件

https://huiqinbo.iteye.com/blog/2192888

这两天需要用python写文件。总结如下:

Python如何让读取文件内容为字符串 ?案例详解

Python如何让读取文件内容为字符串 ?案例详解 - 程序员的人生A - 博客园

https://www.jb51.net/article/143647.htm

#写在原文件中
fp3=open("file3.txt","r+") #不用w w会清空数据
s=fp3.read()#读出 
fp3.seek(0,0) #指针移到头 原来的数据还在是替换 会存在一个问题 如果少  会替换不了全部数据,自已思考解决!
#从头写入
fp3.write(s.replace("hello","good"))
fp3.close()

python删除文件指定行_迷风小白-CSDN博客_python删除txt指定行

import os

lines = (i for i in open('test.txt', 'r') if 'pig' not in i )
f = open('test_new.txt', 'w', encoding="utf-8")
f.writelines(lines)
f.close()
os.rename('test.txt', 'test.bak')
os.rename('test_new.txt', 'test.txt')
os.remove('test.bak')

用python实现文件读取和内容替换 - 矮油~ - 博客园

注意,调用writelines写入多行在性能上会比使用write一次性写入要高。

推荐使用此种方式,但是with之后,会自动关闭f。
    with open('test.dat', 'wb') as f:
        print("open test.dat")
        f.write(mydata)


如果想要循环写入的话
with open("wow_list_dong", "w") as f:
    for a in channels_massage:
        b = a[1] + " " + a[2] + " " + a[3]
        b += "\n"
        f.write(b)

但是有些时候,我们不会同时在一个函数里执行此操作。

global count
count = 0

try:
    f = open('test.dat',  'wb')
    print("open test.dat")
except FileNotFoundError as e:
    print('指定的文件无法打开')
except IOError as e:
    print('读写文件时出现错误.')
    print('程序执行结束.')



def write_file(f, data):
    try:
        f.write(data)
    except FileNotFoundError as e:
        print('指定的文件无法打开')
    except IOError as e:
        print('读写文件时出现错误.')
        print('程序执行结束.')
        f.close()



def func_called(mydata, num):
    # print("print by python,called by cpp!")
    global count
    count+=1
    print("print by python: %s, count: %d" %(str(len(mydata)), count))
    print("the length of %d: %s" %(num, mydata))
    list_data.append(mydata)
    write_file(f, mydata)
    if count == 10:
        count = 0
        f.flush()
        print("flush test.dat count: %d" %(count))
    print("write_file test.dat")

这里注意global count全局变量的使用注意

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值