|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Using the seek() built-in function, create a Python program to replace characters 10, 11, 12, and 13 with the characters GOOD, respectively in the file q16.txt. Note that seek(0) positions at the first character.
For example, if it contained abcdefghijklmnopqrstuvwxyz, the text should be updated to abcdefghiGOODnopqrstuvwxyz.
我的答案:
with open('q16.txt', "r+") as f:
data = f.read()
f.seek(10)
f.write("GOOD")
f.seek(11)
f.write("GOOD")
f.seek(12)
f.write("GOOD")
f.seek(13)
f.write("GOOD")
求解
本帖最后由 ba21 于 2023-8-14 10:55 编辑
注意:
seek( 0)位于第 1 个字符处。
"abcdefghijklmnopqrstuvwxyz" 结果应是: "abcdefghiGOODnopqrstuvwxyz"
重点在于索引位置
- with open("q16.txt", "r+") as file:
- file.seek(10-1)
- file.write("G")
- file.seek(11-1)
- file.write("O")
- file.seek(12-1)
- file.write("O")
- file.seek(13-1)
- file.write("D")
复制代码
就列子中来说,索引是连续的,那么可以一次性来改写,但不知道符不符合题意:
- with open("q16.txt", "r+") as file:
- file.seek(10-1)
- file.write("GOOD")
复制代码
|
|