pyhton 零起点(3)

每次用vim 都要:set nu 挺麻烦的 干脆就直接设置配置文件了 vi ~/.vimrc  添加set nu  就不用那么麻烦了

读取文件

 

 1 # linux.txt 文本里面有三行字
 2 from sys import argv
 3 
 4 script, filename = argv
 5 #打开文件
 6 txt = open(filename)
 7 
 8 print "Here's your file %r: " % filename
 9 print txt.read() #输出文本内容
10 #raw_input打开
11 print "Type the filename again: "
12 filename_again = raw_input("> ")
13 txt_gagin = open(filename_again)
14 print txt_again.raed() 

 

读写文件

  • close – 关闭文件。跟你编辑器的 文件->保存..一个意思。
  • read – 读取文件内容。你可以把结果赋给一个变量。
  • readline – 读取文本文件中的一行。
  • truncate – 清空文件,请小心使用该命令。
  • write(stuff) – 将stuff写入文件。
     1 from sys import argv
     2 
     3 script, filename = argv
     4 
     5 print "We're going to erase %r." % filename
     6 print "If you don't want that, hit CTRL-C (^C)."
     7 print "If you do want that, hit RETURN."
     8 
     9 raw_input("?")
    10 
    11 print "Opening the file..."
    12 target = open(filename, 'w')
    13 
    14 print "Truncating the file.  Goodbye!"
    15 target.truncate()
    16 
    17 print "Now I'm going to ask you for three lines."
    18 
    19 line1 = raw_input("line 1: ")
    20 line2 = raw_input("line 2: ")
    21 line3 = raw_input("line 3: ")
    22 
    23 print "I'm going to write these to the file."
    24 
    25 target.write(line1)
    26 target.write("\n")
    27 target.write(line2)
    28 target.write("\n")
    29 target.write(line3)
    30 target.write("\n")
    31 
    32 print "And finally, we close it."
    33 target.close()

    :自己测试了一下target = open(filename, 'w') 用了'w'模式 不需要target.truncate()效果也是一样的 尝试了一下'w'去掉 发现出错了File not opening for writing
    复制一个文件的内容到另一个文件

     

     1 from sys import argv
     2 from os.path import exists
     3 
     4 script, from_file, to_file = argv
     5 
     6 print "Copying from %s to %s" % (from_file, to_file)
     7 
     8 # we could do these two on one line too, how?
     9 in_file = open(from_file)
    10 indata = in_file.read()
    11 
    12 print "The input file is %d bytes long" % len(indata)
    13 #判断文件是否存在
    14 print "Does the output file exist? %r" % exists(to_file)
    15 print "Ready, hit RETURN to continue, CTRL-C to abort."
    16 raw_input()
    17 
    18 out_file = open(to_file, 'w')
    19 out_file.write(indata)
    20 
    21 print "Alright, all done."
    22 
    23 out_file.close()
    24 in_file.close()
    25  

     

    :有一个奇怪的问题就是 你的to_file里面的原本内容会被清除

     

 

 

转载于:https://www.cnblogs.com/linuxroot/archive/2012/11/20/2778475.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值