在Python编程中,内置的open函数允许我们以不同的模式打开文件进行读写操作。这些模式各有特点,用于解决不同的需求。
1. r: 打开并读取文件。如果文件不存在,会抛出FileNotFoundError异常。 2. w: 写入文件。如果文件存在,内容会被覆盖。如果文件不存在,创建一个新的文件。 3. a: 在文件的末尾追加写入。如果文件存在,内容会在文件的末尾追加。如果文件不存在,创建一个新的文件。 4. r+: 打开并读写文件。如果文件不存在,会抛出FileNotFoundError异常。 5. w+: 写入并读写文件。如果文件存在,内容会被覆盖。如果文件不存在,创建一个新的文件。 6. a+: 在文件的末尾追加读写。如果文件存在,内容会在文件的末尾追加。如果文件不存在,创建一个新的文件。
下面是一个简单的代码示例,展示了如何使用这些模式打开一个文件进行读写:
```python # 打开并读取文件 with open('example.txt', 'r') as f: content = f.read() print(content)
# 写入文件 with open('example.txt', 'w') as f: f.write('Hello, world!')
# 在文件的末尾追加写入 with open('example.txt', 'a') as f: f.write('\\nThis is appended content.')
# 打开并读写文件 with open('example.txt', 'r+') as f: content = f.read() print(content) f.seek(0, 2) # 将文件指针移动到文件的末尾 f.write('\\nThis is appended content in r+ mode.')
# 在文件的末尾追加读写 with open('example.txt', 'A+') as f: content = f.read() print(content) f.seek(0, 2) # 将文件指针移动到文件的末尾 f.write('\\nThis is appended content in A+ mode.') ```
这个示例中,我们首先以只读模式打开并读取一个文件,然后以写模式写入内容,接着在文件的末尾追加写入内容。然后我们再次以读写模式打开并读取文件,然后在文件的末尾追加读写内容。
测试用例:
```python # 假设example.txt文件内容为'Hello, world!' with open('example.txt', 'r') as f: content = f.read() assert content == 'Hello, world!', "Test case failed."
with open('example.txt', 'w') as f: f.write('Hello, Python!')
with open('example.txt', 'r') as f: content = f.read() assert content == 'Hello, Python!', "Test case failed."
with open('example.txt', 'A') as f: f.write('\\nHello, again!')
with open('example.txt', 'r') as f: content = f.read() assert content == 'Hello, Python!\\nHello, again!', "Test case failed."
with open('example.txt', 'r+') as f: content = f.read() assert content == 'Hello, Python!\\nHello, again!', "Test case failed." f.seek(0, 2) # 将文件指针移动到文件的末尾 f.write('\\nHello, again in r+ mode!')
with open('example.txt', 'r') as f: content = f.read() assert content == 'Hello, Python!\\nHello, again!\\nHello, again in r+ mode!', "Test case failed."
with open('example.txt', 'A+') as f: content = f.read() assert content == 'Hello, Python!\\nHello, again!\\nHello, again in r+ mode!', "Test case failed." f.seek(0, 2) # 将文件指针移动到文件的末尾 f.write('\\nHello, again in A+ mode!')
with open('example.txt', 'r') as f: content = f.read() assert content == 'Hello, Python!\\nHello, again!\\nHello, again in r+ mode!\\nHello, again in A+ mode!', "Test case failed." ```
如果要对这个模式进行测试,可以使用Python的unittest库。
评论前必须登录!
注册