笨方法自学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看看里面是什么

相关推荐
a9511416428 分钟前
SQL触发器实现自动生成流水号_配合序列对象实现递增逻辑
jvm·数据库·python
哦哦~92113 分钟前
FDTD 与 Python 联合仿真的超表面智能设计技术与应用
python·fdtd·超表面
财经资讯数据_灵砚智能13 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年4月21日
人工智能·python·信息可视化·自然语言处理·ai编程
解救女汉子19 分钟前
mysql如何配置元数据锁超时_mysql lock_wait_timeout设置
jvm·数据库·python
214396542 分钟前
SQL注入防御技术方案_基于正则表达式的输入清洗
jvm·数据库·python
2401_832365521 小时前
SQL窗口函数与递归查询的区别_如何根据场景选择
jvm·数据库·python
u0109147601 小时前
c++如何处理文件路径中由于不规范的连续斜杠导致的路径解析错误【避坑】
jvm·数据库·python
2301_796588501 小时前
PHP源码开发用二手硬件划算吗_性价比与稳定性权衡【操作】
jvm·数据库·python
2301_775148151 小时前
如何通过C#读取Oracle数据库中的图片显示到WinForm_BLOB转Byte[]与流处理
jvm·数据库·python
小饕1 小时前
RAG学习之- RAG 数据导入完整指南
人工智能·python·学习