这个创建的文本文件包含两个单词“Hello World”,这是作业要求的。当我尝试向代码中添加打印(openfile.read())行时,没有得到任何返回:
import os
# Complete the function to append the given new data to the specified file then print the contents of the file
def appendAndPrint(filename, newData):
# Student code goes here
openfile = open(filename, 'a+')
openfile.write(newData)
print(openfile.read())
return
# expected output: Hello World
with open("test.txt", 'w') as f:
f.write("Hello ")
appendAndPrint("test.txt", "World")
函数应该返回带有该语句的行“Hello World”,我是否将打印代码放在了错误的位置
写入文件后,需要将其关闭
.close()
。然后用open('test.txt', 'r+)
再次打开它写入文件后,必须倒带(查找) 在阅读之前,把它放回到开头
在print语句之前添加以下行
seek及其参数的文档 https://docs.python.org/3/library/io.html?highlight=seek#io.IOBase.seek
请注意,如果要从同一进程(有线程或无线程)中读取新写入的文件,seek是最好、最有效的方法
附录:(进程间场景) 但是,如果要从另一个进程读取该文件,则必须刷新该文件或将其关闭。(如果您想继续在流程中读写,则首选刷新方式
假设您有两个脚本:
脚本1.py
脚本2.py
相关问题 更多 >
编程相关推荐