笨方法自学python(九)-读写文件

读取文件

前面已经学过了 input 和 argv,这些是你开始学习读取文件的必备基础。你可能需要多多实验才能明白它的工作原理,这节练习涉及到写两个文件。一个正常的 ex15.py 文件,另外一个是 ex15_sample.txt,第二个文件并不是脚本,而是供你的脚本读取的文本文件。以下是后者的内容:

bash 复制代码
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

我们要做的是把该文件用我们的脚本"打开(open)",然后打印出来。

以下是ex15.py的程序

python 复制代码
from sys import argv
script, filename = argv
txt = open(filename)
print("Here's your file %r:"%filename)
print(txt.read())
print("Type the filname again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())

运行结果:

读写文件

需要记住以下命令:

  1. close -- 关闭文件。跟你编辑器的 文件->保存... 一个意思。
  2. read -- 读取文件内容。你可以把结果赋给一个变量。
  3. readline -- 读取文本文件中的一行。
  4. truncate -- 清空文件,请小心使用该命令。
  5. write(stuff) -- 将 stuff 写入文件。

例题:

python 复制代码
from sys import argv

script,filename = argv

print("we're going to erase %r." %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("Now I'm going to ask you for three lines.")

line1 = input("line1:")
line2 = input("line2:")
line3 = input("line3:")

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

运行结果:

line1,line2,line3后面是我们自己输入的,运行完毕后打开 test.txt看看里面是什么

相关推荐
叫我:松哥11 分钟前
基于Python flask的医院管理学院,医生能够增加/删除/修改/删除病人的数据信息,有可视化分析
javascript·后端·python·mysql·信息可视化·flask·bootstrap
Eiceblue41 分钟前
Python 复制Excel 中的行、列、单元格
开发语言·python·excel
NLP工程化1 小时前
对 Python 中 GIL 的理解
python·gil
极客代码1 小时前
OpenCV Python 深度指南
开发语言·人工智能·python·opencv·计算机视觉
liO_Oil1 小时前
(2024.9.19)在Python的虚拟环境中安装GDAL
开发语言·python·gdal安装
奈斯。zs1 小时前
yjs08——矩阵、数组的运算
人工智能·python·线性代数·矩阵·numpy
Melody20501 小时前
tensorflow-dataset 内网下载 指定目录
人工智能·python·tensorflow
学步_技术1 小时前
Python编码系列—Python抽象工厂模式:构建复杂对象家族的蓝图
开发语言·python·抽象工厂模式
Narutolxy2 小时前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
Amo Xiang2 小时前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python