• 《笨办法学Python》 第17课手记


    《笨办法学Python》 第17课手记

    本节内容是前几节内容的复习和综合,此外引入了exists函数。

    原代码如下:

    
    from sys import argv
    from os.path import exists
    
    script, from_file, to_file = argv
    
    print "Copying from %s to %s" %(from_file, to_file)
    
    #we could do these two on the line too, how?
    in_file = open(from_file)
    indata = in_file.read()
    
    print "The input file is %d bytes long" % len(indata)
    
    print "Does the output file exist? %r" % exists(to_file)
    print "Ready, hit RETURN to comtinue, CTRL-C to abort."
    raw_input()
    
    out_file = open(to_file, 'w')
    out_file.write(indata)
    
    print "Alright,all done."
    
    out_file.close()
    in_file.close()

    结果如下:
    这里写图片描述

    这里写图片描述

    exists函数是检查括号内字符串所代表的文件名的文件是否存在,存在返回True,不存在返回False。

    请注意,这里作者所说的复制并不是使用了一个专门用来复制字符的函数,而是采用了变量赋值的方式实现复制。

    in_file = open(from_file) #将open函数得到的结果(是一个文件,而不是文件的内容)赋值给in_file。
    indata = in_file.read()   #使用read函数读取文件内容,并将文件内容赋值给indata。

    剩下的在作者的常见问题解答中有提到,这里不再赘述。

    本节课涉及的内容

    cat 在C语言字符串操作里strcat也表示字符串连接的意思str(char dst, cahr src)中,如果dst是空的,也就是将src复制到dst的意思。

    至于windows中cat的替代品。显示的话用的是Type,复制的话是copy。

    len(),该函数返回的长度是指字节数。

    indata = open(from_file).read(),是一种简化的写法,如果你想化简上面的代码,可以尝试使用这种形式来写。

    下面是可能的一种简写方法,一行写出来我做不到,除非使用cat。

     from sys import argv
     script, from_file, to_file = argv
     to_file = open(to_file, 'w') 
     to_file.write( open(from_file).read())
    
    
  • 相关阅读:
    xgboost
    GBDT 梯度提升决策树简述
    minimal pairs
    Describe your hometown
    英语短句
    英汉翻译
    英语音译词
    power的读音
    英语口语(英语词根与单词的说文解字(李平武 2008版)读书笔记)
    Jar包转成Dll的方式(带嵌套的jar也能做)
  • 原文地址:https://www.cnblogs.com/wanghongze95/p/13842706.html
Copyright © 2020-2023  润新知