【发布时间】:2021-04-19 21:26:10
【问题描述】:
我有这个作业,我需要定义一个执行以下操作的函数:
写一个函数,给定一个以读写模式打开的文本文件对象和一个字符串,将字符串的文本插入文件中当前读/写位置。换句话说,该函数将字符串写入文件而不覆盖其余部分。退出函数时,新的读/写位置必须正好在新插入的字符串的末尾。 算法简单;该功能需要:
- 从当前读/写位置开始读取文件内容
- 在步骤 1 开始的相同位置写入给定字符串
- 将第1步读取的内容写入第2步结束的位置
- 将读/写光标重新定位在同一位置 step2。结束(第 3 步开始)。
步骤 1-4 让我很困惑我需要做什么,教授也没有帮助。
这是我做的代码,但我不认为函数遵循给定的参数
def readWrite(file, string):
file.read()
file.seek(0)
file.write(string)
give_file = input("enter a file name: ")
give_string = input("enter a string: ")
try:
readFile = open(give_file, "a+")
file_content = readWrite(readFile, give_string)
except FileNotFoundError:
print("File does not exist")
exit(1)
整个代码应该请求一个简单的.txt 文件,它将接受它和一个字符串,并将其添加到原始文件中。
示例: 文件是 Twinkle.txt
Twinkle, twinkle, little bat!
How I wonder what you're at!
Up above the world you fly,
Like a teatray in the sky.
输出:
twinkle.txt
1 Twinkle, twinkle, little bat!
2 How I wonder what you're at!
3 Up above the world you fly,
4 Like a teatray in the sky.
【问题讨论】:
-
按步骤 1 到 4?喜欢整个作业吗?
-
@Matiiss 它唯一的功能。主体只是调用函数并为行编号(仍在弄清楚)
-
还有你为什么要退出 3 个不同的退出代码?我会假设这是为了跟踪程序退出的功能
-
@Matiiss 我认为需要将 2 个功能合二为一。但我很困惑,所以不知道该怎么做
-
@MMSS19 也许看看我对类似问题的回答。我很确定这就是你要找的东西。如果有帮助,别忘了点赞 :) stackoverflow.com/questions/66482152/…
标签: python python-3.x function file