美文网首页
2018-04-27笨办法学python-17更多文件操作

2018-04-27笨办法学python-17更多文件操作

作者: 轻飏921 | 来源:发表于2019-06-22 14:52 被阅读0次

    1.看看你能把这个脚本改多短:

    open('chen1.txt','w').write(open('chen.txt').read())

    #忘记加引号查了好久。。。

    ///

    为什么 'w' 要放在括号中?因为这是一个字符串。

    这不是打印,所以文件名是字符串,w是字符串,要加引号。

    2.windows将文件内容打印到屏幕上的命令:type

    3.为什么你需要在代码中写 output.close()

    因为这个文件有打开操作。

    4.代码修改的稍微短一些

    from sys import argv

    from os.path import exists

    script, from_file,to_file =argv

    out_file = open(to_file,'w')

    out_file.write(open(from_file).read())

    out_file.close()

    in_file.close()

    执行会报错:

    因为,如果代码格式是:indata = open(from_file).read() 这意味着你无需再运行

    ``in_file.close()`` 了,因为 read() 一旦运行, 文件就会被读到结尾并且被 close 掉。

    把close()代码注释后程序运行不报错。

    5.exist :判断文件或文件夹是否存在,存在返回True,不存在返回False

    相关文章

      网友评论

          本文标题:2018-04-27笨办法学python-17更多文件操作

          本文链接:https://www.haomeiwen.com/subject/tshilftx.html