美文网首页
python3学习笔记--文件

python3学习笔记--文件

作者: 谢懵逼 | 来源:发表于2019-04-07 22:58 被阅读0次

文件

相关函数

  • close:关闭文件
  • read:读取文件的内容,可以把结果赋值给一个变量
  • readline:只读取文本文件中的一行
  • truncate:清空文件【谨慎使用】
  • write('stuff'):将'stuff'写入文件
  • seek(0):将读写位置移动到文件开头

读取文件

  • 使用open()获取文件对象 2.使用read()读取内容
  • eg
from sys import argv 
scrpit,fliename = argv 
txt = open(fliename) 
print(f"Here's your file {fliename}") print(txt.read())
txt.close()

读写文件

  • eg
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()

  • 传入的值
    • 传入 'w': “写入(write)模式”
    • 传入'r' : ”读取(read)“
    • 传入'a' : "追加(append)"
    • open(filename) ,不加传入的值表示用只读模式打开

复制文件内容

  • 判断文件是否存在
    • 使用exitsts
    • 导入方法:from os.path import exists
  • eg
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()

相关文章

网友评论

      本文标题:python3学习笔记--文件

      本文链接:https://www.haomeiwen.com/subject/rizeiqtx.html