019、文件读写
本文最后更新于 67 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com

文件读写

写入测试文件:

%%writefile test.txt
this is a test file.
hello world!
python is good!
today is a good day.
Writing test.txt

读文件

使用 open() 函数来读文件,使用文件名的字符串作为输入参数:

f = open('test.txt')

可以使用 .read()方法来读入文件中的所有内容:

text = f.read()
text
'this is a test file.\nhello world!\npython is good!\ntoday is a good day.\n'
print(text)
this is a test file.
hello world!
python is good!
today is a good day.

使用完文件之后,需要将文件关闭:

f.close()

也可以用.readlines()方法按照行读入内容。该方法返回一个列表,每个元素代表文件中每一行的内容:

f = open('test.txt')

lines = f.readlines()

f.close()

print(lines)
['this is a test file.\n', 'hello world!\n', 'python is good!\n', 'today is a good day.\n']

还可以将f放入一个循环中,遍历:

f = open('test.txt')
for line in f:
    print(line)
f.close()
this is a test file.

hello world!

python is good!

today is a good day.

删除演示文件:

%rm test.txt

写文件

写文件也使用open()函数,只需要额外指定模式参数为w

f = open('myfile.txt', 'w')
f.write('hello world!')
f.close()

使用 w 模式时,如果文件不存在会被创建:

print(open('myfile.txt').read())
hello world!

如果文件存在,原先的内容会被完全覆盖:

f = open('myfile.txt', 'w')
f.write('another hello world!')
f.close()
print(open('myfile.txt').read())
another hello world!

如果不想覆盖,则需要使用追加模式a

f = open('myfile.txt', 'a')
f.write('... and more')
f.close()
print(open('myfile.txt').read())
another hello world!... and more

删除演示文件:

%rm myfile.txt
谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇