笨办法python3 17

1.复制文件内容from sys import argvfrom os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
indata = open(from_file).read()
print(f"The input file is {len(indata)} bytes long")
print(f"Does the output file exist? {exists(to_file)}")print(“Ready, hit RETURN to continue, CTRL-C to abort.”)input()
out_file = open(to_file,‘w’)out_file.write(indata)
print(“Alright, all done.”)
out_file.close()
2.判断文件是否存在 exists函数from os.path import existsfile_path = '…'print(exists(file_path)) 注意需要从os.path中导入exists函数以文件名字符串作为参数,返回值为True/False。
3.在Poweshell命令行中创建和显示文件创建文件并写入内容echo “This is a test”> test.txt显示文件内容cat test.txt
4.打开文件并使用完后要及时用close()关闭原因:①文件打开占用系统资源,只有进程关闭时才会释放掉,但一个进程能利用的资源有限,及时关闭以释放资源②文件内容不能即时 flush 到磁盘直到进程结束。也就是说如果突然断电,内容会大部分丢失?
5.遇到过以下errorUnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xff in position 0: illegal multibyte sequence意思是txt中有gbk无法解码的内容,然而看起来并没有,暂时没有找到是什么原因。删除txt重新创建以后运行正常。6.区别file = open(path)indata = file.read()这时先将文件打开到file,再read,两行结束后文件并没关闭,需要使用完再用closeindata = open(path).read()未经过中间量,直接read,由于read()一旦运行完程序就会关闭,因此这之后用close会报错

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值