slacr_

Just to record my life and thoughts.
笔记/编程/杂乱/极简

[Python]文件

Sep 7, 2023Python770 words in 5 min

文件

打开文件

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-

f = open('dairy.txt', 'w')
# 如果一个文件不存在会报异常, 写入模式让你能够写入文件,并在文件不存在时创建它。
# 在写入模式下打开文件时,既有内容将被删除(截断),并从文件开头处开始写入;如果要在既有文件末
# 尾继续写入,可使用附加模式

f1 = open('dairy1.txt', 'x')
# 独占写入模式不允许文件已存在

默认模式为’rt’,这意味着将把文件视为经过编码的Unicode文本,因此将自动执行解码和编码,且默认使用UTF-8编码。要指定其他编码和Unicode错误处理策略,可使用关键字参数encoding和errors。默认情况下,行以’\n’结尾。读取时将自动替换其他行尾字符(‘\r’或’\r\n’);写入时将’\n’替换为系统的默认行尾字符(os.linesep)。

文件基本方法

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-

with open('dairy.txt', 'w') as f:
f.write("真是寂寞如雪啊~")


with open('dairy.txt', 'r') as f:
ctx = f.readline()
print(ctx)

管道重定向

三个标准流: sys.stdin, sys.stdout, sys.stderr

1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-

import sys
text = sys.stdin.read()
words = text.split()
wordcount = len(words)
print('Wordcount:', wordcount)

# cat .\dairy.txt | python .\script.py

随机存取

seek 和 tell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding: utf-8 -*-

with open('./dairy.txt', 'w+') as f:
f.seek(5)
print(f.tell())
f.write("test")
print(f.tell())

with open('./dairy.txt', 'r+') as f:
f.seek(5)
s = f.read(4)
print(s)

# seek移动指针, tell返回指针位置

可使用方法read并不提供任何参数(将整个文件读取到一个字符串中),readlines(将文件读取到一个字符串列表中,其中每个字符串都是一行)

一些迭代

1
2
3
import fileinput
for line in fileinput.input(filename):
process(line)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
with open(filename) as f: 
char = f.read(1)
while char:
process(char)
char = f.read(1)

# %%
with open(filename) as f:
while True:
char = f.read(1)
if not char: break
process(char)

# %%
with open(filename) as f:
while True:
line = f.readline()
if not line: break
process(line)

# %%
with open(filename) as f:
for char in f.read():
process(char)

# %%
with open(filename) as f:
for line in f.readlines():
process(line)

# %% 文件是可迭代的
with open(filename) as f:
for line in f:
process(line)

# %%
for line in open(filename):
process(line)

# %% sys.stdin也是可迭代的
import sys
for line in sys.stdin:
process(line)
# 这可以实现不用fileInput实现文件流输入, 使用管道符重定向个文件输入

# %%

1
2
3
4
5
6
7
8
9
10
11
12
# -*- coding: utf-8 -*-
import sys

f = open('./content.txt', 'w')
print('First', file=f)
print('Second', file=f)
print('Thrid', file=f)
# print的默认输出是sys.stdin, 重定向到文件
f.close()

with open('./content.txt') as f:
print(list(f))
  1. Fluent Python
  2. python核心编程
  3. python基础教程第三版
  4. Python Packaging
  • Author:

    slacr_

  • Copyright:

  • Published:

    September 7, 2023

  • Updated:

    September 7, 2023

Buy me a cup of coffee ☕.

1000000