@mdjsjdq
2016-01-07T22:57:11.000000Z
字数 1058
阅读 1830
Python
用法
copy_files.py from_file to_file
,就可以把文本(.txt 文件格式)文件复制
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Filename : copy_file.py
import sys
from os.path import exists # 这样的py脚本不太好
script,from_file,to_file = sys.argv
print "Cpoying from %s to %s." % (from_file,to_file),"\n"
print """
I wanna to use Pyhton to copy files like from_file to to_file. "\n"
"""
in_file = open(from_file)
in_data = in_file.read() # 先打开才能读取,最后还要关闭
print "The input file is %d bytes long" %len(in_data),"\n"
print "Does the outfiles exist? %r" %exists(to_file) #这段代码比较有意思,很重要\
# 要是文件不存在就创建一个文件
print "Ready please press Enter to contiue,Ctrl + C to abort.","\n"
raw_input()
to_file = open(to_file,"w")
to_file.write(in_data)
print "Aright ,all done."
to_file.close()
in_file.close()
类似于Unix\Linux上的cat命令,可以查看一个文本文件的内容,用法:
cat.py flie
#!/usr/bin/python
# coding = utf-8
# Filename: cat.py
import sys
def readfile(filename):
'''Print a file to the standard output.'''
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line, # notice comma(注意逗号)
f.close()
for filename in sys.argv[1:]:
readfile(filename) # 本程序完全没问题
#是sys.argv[1:]代表着其中的非本程序的文件,要是本程序的问你安默认是sys.argv[0:]