《笨办法学Python》习题15

  1. pydoc:python自带的一个文档生成工具,通过它可以查看类和方法和模块的结构

  2. open()函数用法

`open(file, mode=‘r’, buffering=-1, encoding=None, errors=None,
newline=None, closefd=True, opener=None)
***file:文件名;
mode:对文件以指定的模式打开,如读、写等,
默认为“r”,意思是打开阅读文本模式。
“w”表示写入,
“x”用于创建和写入新,
“a”表示附加,
’ b '二进制模式
“t”文本模式(默认)
“+”打开磁盘文件进行更新(读写)
“u”通用换行符模式(已弃用)
buffering:间隔;encoding:编码;
(接触了之后的再来补)


Open file and return a stream.  Raise OSError upon failure.

file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode.  Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:

========= 

3.所读取文件需在Python运行所打开的文件夹内,不然会找不到该文件

from sys import argv
script, filename = argv
#给argv两个参数定义,一个是执行的Python文件名,一个是代码内部要打开文件名
txt = open(filename)
#txt打开文件位置
print('the file will be open %r:'%filename)
#打印文件名
print (txt.read())
#读取文件内容
print ("Type the filename again:")
file_again = input(">")
#输入文件名
txt.again = open(file_again)
#打开文件位置
print (txt.again.read())
#打印文件内容

这段代码写了两种读取文件的方式,一个是通过argv参数定义,在运行开始就直接输入想要打开的文件名,而第二种方法是input,进入互动界面再进行打开。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值