zoukankan      html  css  js  c++  java
  • 练习17--更多文件

    一 相关知识

    1 exists命令:

    功能:基于一个字符串里面的变量文件名来判断文件是否存在,如果存在,返回 True ;不存在,返回 False 。

    注意:在脚本中使用该命令需要导入:from os.path import exists

    2 cat命令

    功能:用于连接文件并打印到标准输出设备上。

    语法:cat  文件名

    学习:可以使用man cat命令来看看关于这个命令的作用。

    3 len函数

    len()函数是什么作用? 它能够取字符串的长度,然后返回一个数字
     
    4 在我试着把这些代码缩短的时候,我在关闭文件文件时遇到了错误。。 你可能用了indata = open(from_file).read() ,这意味着你不需要在之后再输入 in_file.close() ,因为
    你已经到了脚本的最后。一旦那一行运行过之后,它就已经被 Python 关掉了。
     
    5 我收到了一个这样的的错误:: Syntax:EOL while scanning string literal 。。 你忘了在字符串后面加引号了,再检查一遍的代码。
     
    二 代码及运行结果
    1 程序代码
    from sys import argv
    from os.path import exists
    
    script,from_file,to_file = argv
    
    # 打印该脚本的功能:复制文件
    print(f"Copy from {from_file} to {to_file}")
    
    # 打开要复制的源文件并读取文件中的数据
    # we could do these two on one line,how?
    in_file = open(from_file)
    indata = in_file.read()
    
    # 打印源文件中数据的大小
    print(f"The input file is {len(indata)} bytes long")
    
    # 判断复制后得到的目标文件是否存在
    # 实际中结果是不存在,所以说我们在用argv传递一个to_file文件的时候,
    # 是不是只是相当于定义了一个名字,而这个名字还没有被赋值
    # 在执行完打开文件操作之后该文件才存在,可以判断一下:31行:print(exists(to_file))
    print(f"Does the output file exists?{exists(to_file)}")
    
    # 判断是否要继续复制文件
    print("Ready,hit RETURN to continue,CTRL-C to abort.")
    input()
    
    # 以可写模式打开to_file文件并将源文件中的数据写入
    out_file = open(to_file,'w')
    out_file.write(indata)
    
    print(exists(to_file))
    
    print("Alright,all done.")
    
    # 关闭文件
    out_file.close()
    in_file.close()

    2 执行结果

    PS E:3_work4_python2_code_python2_LearnPythonTheHardWay> python ex17.py test.txt  new_file.txt
    Copy from test.txt to new_file.txt
    The input file is 11 bytes long
    Does the output file exists?False
    Ready,hit RETURN to continue,CTRL-C to abort.
    RETURN
    True
    Alright,all done.
  • 相关阅读:
    使用::befor和::after伪元素在网站中添加图标
    使用LESS对CSS进行预处理
    window.innerWidth和document.body.clientWidth的区别
    javascript原型链继承
    javascript中的类型检测
    ASP.NET网站报Service Unavailable错误的解决办法
    在ASP.NET MVC中使用UEditor无法提交的解决办法
    EasyUI DataGrid设置列宽为百分比导致表头和内容错位的解决方法
    使用JS读取本地文本文件(兼容各种浏览器)
    美化上传文件按钮
  • 原文地址:https://www.cnblogs.com/luoxun/p/13228071.html
Copyright © 2011-2022 走看看