python 档案管理系统_Python 写入档案的 4 个方法

在 Python 写入档案内容跟读取档案差不多, 也很简单方便,以下会介绍用 Python 逐行读取档案内容的 4 种方法。

在看例子前先要了解开启档案的参数, 一般上读取档案会用 “r”, 即唯读的意思, 如果要写入档案, 分别可以用 “w” (即 write 的意思) 或 “a” (即 append 附加的意思), 两者的分别在于: 如果档案原本已经存在, “w” 会将写入的内容直接覆蓋原来的档案内容; 而 “a” 则会在原来的内容后面加入新内容。两者不可以混淆, 如果原本要用 “a” 而用错了 “w”, 会使原来的档案内容错误删除。

以下所有例子会以 “a” 作为开启档案选项。

write

#!/usr/bin/python

# 开启档案

fp = open("filename.txt", "a")

# 写入 This is a testing! 到档案

fp.write("This is a testing!")

# 关闭档案

fp.close()

1

2

3

4

5

6

7

8

9

10

#!/usr/bin/python

# 开启档案

fp=open("filename.txt","a")

# 写入 This is a testing! 到档案

fp.write("This is a testing!")

# 关闭档案

fp.close()

print

档开启档案后, 可以用输出文字的 print 写入档案, 只是将原本输出到显示器改为档案:

#!/usr/bin/python

# 开启档案

fp = open("filename.txt", "a")

# 写入 This is a testing! 到档案

print >>fp, "This is a testing!"

# 关闭档案

fp.close()

1

2

3

4

5

6

7

8

9

10

#!/usr/bin/python

# 开启档案

fp=open("filename.txt","a")

# 写入 This is a testing! 到档案

print>>fp,"This is a testing!"

# 关闭档案

fp.close()

writelines

可以将 array 的内容一次过写入写案, 但要自行加入 “\n” 到每一个换行:

#!/usr/bin/python

# 开启档案

fp = open("filename.txt", "a")

# 将 lines 所有内容写入到档案

lines = ["One\n", "Two\n", "Three\n", "Four\n", "Five\n"]

fp.writelines(lines)

# 关闭档案

fp.close()

1

2

3

4

5

6

7

8

9

10

11

#!/usr/bin/python

# 开启档案

fp=open("filename.txt","a")

# 将 lines 所有内容写入到档案

lines=["One\n","Two\n","Three\n","Four\n","Five\n"]

fp.writelines(lines)

# 关闭档案

fp.close()

with

用 wite 写入档案, 跟上面最大分别是, 不用 close() 关闭档案:

#!/usr/bin/python

with open(in_filename) as in_file, open(out_filename, 'a') as out_file:

for line in in_file:

...

...

out_file.write(parsed_line)

1

2

3

4

5

6

7

#!/usr/bin/python

withopen(in_filename)asin_file,open(out_filename,'a')asout_file:

forlineinin_file:

...

...

out_file.write(parsed_line)

你可能感兴趣的内容:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值