我需要写一个函数,给定一个在读写模式下打开的文本文件对象和一个字符串,将字符串的文本插入文件中当前的读写位置。换句话说,函数在文件中写入字符串,而不覆盖其余部分。退出函数时,新的读/写位置必须正好位于新插入字符串的末尾。 算法简单;该功能需要:
如果参数文件对象不可读写,函数应该打印消息并立即返回,而不做任何更改。
这可以通过使用方法file object methodsreadable()
和writable()
来实现
在主脚本中:
1-提示用户输入文件名
2-以读写模式打开文件。如果找不到该文件,请打印一条消息并退出程序
3-插入文件名,作为文件的第一行,后跟空行
4-在原始文本的每行开头插入行号和空格
我对如何编写函数和主体感到非常困惑。 到目前为止,我只有
def openFile(fileToread):
print(file.read())
givefile = input("enter a file name: ")
try:
file = open(givefile, "r+")
readWriteFile = openFile(file)
except FileNotFoundError:
print("File does not exist")
exit(1)
print(givefile, "\n")
这并不多
我需要这样的输出:
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.
使用的文件是一个带有闪烁歌曲的简单.txt文件 我该怎么做
基本溶液
这会给你预期的结果
我询问了
r+
以及如何在本例中使用它。我得到了这个答案:因此,您的代码是:
建议
不要使用函数,它隐藏了一个事实,即使用方法时会产生一些副作用(移动光标)。 相反,直接调用该方法,这样更好:
或者,使用基本解决方案和功能
相关问题 更多 >
编程相关推荐