python3学习笔记--文件

2019-04-07  本文已影响0人  谢懵逼

文件

相关函数

读取文件

from sys import argv 
scrpit,fliename = argv 
txt = open(fliename) 
print(f"Here's your file {fliename}") print(txt.read())
txt.close()

读写文件

from sys import argv 
scrpit, filename = argv 
print(f"We're going to erase{filename}.") 
print("If you don't want that,hit CTRL_C(^C)") print(" If you do want that,hit RETURN")
input("?")
print("Opening the file...")
target = open(filename,'w') 
print("Truncating the file.Goodbye!") target.truncate() 
print("I'm going to ask you for this lines.") 
line1 = input("line 1") 
line2 = input("line 2")
line3 = input("line 3") 
print("I'm going to write these to the file.") target.write(line1) 
target.write("\n")
target.write(line2) 
target.write("\n") target.write(line3) target.write("\n")
print("And finally,we close it.") 
target.close()

open()

复制文件内容

from sys import argv 
from os.path import exists

script,from_file,to_file = argv 

print (f"Coping from {from_file} to {to_file}")
in_file = open(from_file)
indatas = in_file.read() 

print(f"The input file is {len(indatas)} bytes long")

print(f"Does the output file exitst? {exists(to_file)}") 
print("Ready,hit RETURN to continue,CTRL-C to abort") 
input() 

out_file = open(to_file,'w')
out_file.write(indatas) 

print("Alright,all done") 

out_file.close() in_file.close()
上一篇 下一篇

猜你喜欢

热点阅读