更多文件操作
前情提要
exists命令将文件名字符串作为参数,如果文件存在,它将返回True,否则返回False
代码如下
from sys import argv
from os.path import exists
script, from_file, to_file = argv,'from_file','to_file'
print(f'copying from {from_file} to {to_file}')
#we could do these two on one line,how?
in_file = open('from_file.txt')
indata = in_file.read()
print(f'The input file is {len(indata)} bytes long')
print(f'Does the output file exist?{exists(to_file)}')
print('Ready,hit RETURN to continue,CTRL-C to abort.')
input()
out_file = open('to_file.txt','w')
out_file.write(indata)
print('Already,all done.')
out_file.close()
in_file.close()
结果输出
copying from from_file to to_file
The input file is 0 bytes long
Does the output file exist?False
Ready,hit RETURN to continue,CTRL-C to abort.
Already,all done.
进程已结束,退出代码0
巩固练习
1. 你能把脚本改多短?
from sys import argv
script, from_file, to_file = argv,'from_file','to_file';in_file = open('from_file.txt');indata = in_file.read();out_file = open('to_file.txt','w');out_file.write(indata)
##############
script, from_file, to_file = argv,'from_file','to_file'
cat=('''in_file = open('from_file.txt');indata = in_file.read();out_file = open('to_file.txt','w');out_file.write(indata)''')
2. 'cat’命令是将两个文件拼接(concatenate)到一起,实际用途是打印,通过man cat了解更多的信息
3. 为什么需要在代码写out_file.close()
为了不让代码继续循环
Tips
1. 为什么‘w’要在引号中?
这是一个字符串。
2. 不要把这些放在一行里!
取决于这行代码如何定义。提示:That;depends;on;how;you;define;one;line;of;code.
3. len()函数的功能
以数值的形式返回你传递的字符串的长度。
4. 报错
syntax:EOL white scanning string literal.
#忘记在字符串加引号