Python学习17:使用Python拷贝文本文件
2018-02-22 23:43
369 查看
编写一个Python脚本,将一个文件的内容拷贝到另一个文件
使用import整个模块的方式改写代码:
# -- coding: utf-8 -- 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 one line too, how? # input = open(from_file) # indata = input.read() indata = open(from_file).read() #print "Here is indata: %r" % indata #print #print indata print "The input file is %d bytes long" % len(indata) print "Does the output file exists? %r" % exists(to_file) print "Ready, hit RETURN to continue, CTRL-C to abort." raw_input("RETURN or CTRL-C > ") # 如果to_file不存在的话,程序会自动在脚本当前目录创建文件,文件名为你给的第二个参数 output = open(to_file, 'w') output.write(indata) print "Alright, all done." output.close() print print indata
使用import整个模块的方式改写代码:
import sys #导入sys模块,可以读写文件内容 import os #导入os模块,可以使用exists方法查询文件是否存在 script, from_file, to_file = sys.argv input = open(from_file) indata = input.read() print "Does the output file exists? %r" % os.path.exists(to_file) raw_input("continue? 'RETURN' for continue, 'CTRL-C' for abort. >") output = open(to_file, 'w') output.write(indata) print "Alright, done." output.close() input.close()
相关文章推荐
- python学习笔记:深浅拷贝的使用和原理
- Python 使用 Xlrd/xlwt 操作 Excel 分类: python基础学习 2014-03-17 12:06 958人阅读 评论(0) 收藏
- Python学习 之 对内存的使用(浅拷贝和深拷贝)
- python学习1-使用类
- python学习2-使用list
- [Python学习]使用minidom来处理XML的示例 (二)–XML的写入
- python学习3-使用dict
- 使用minidom来处理XML的示例(Python 学习)(转载)
- 使用QTextStream实现文本文件拷贝
- 使用minidom来处理XML的示例(Python 学习)(转载)
- mongoDB学习笔记3--python下使用
- 每个程序员都应该学习使用Python或Ruby
- 每个程序员都应该学习使用Python或Ruby
- 正则表达式使用学习(C++、Qt、Python)
- [Python学习]使用minidom来处理XML的示例 (三)–XML的美化
- Asp.Net Ajax 学习笔记17 使用Authentication Service
- 重新学习python线程应用使用thread类,改写程序
- Atlas学习手记(17):使用FilteredTextBox过滤字符
- 使用QTextStream实现文本文件拷贝
- 转载:如何使用python将文本文件转化为XML文件