尝试读取文件时,实际文件具有正确的文本,.read()没有显示任何内容:

杰森·阿诺德(Jason Arnold)

此创建的文本文件中有两个单词“ Hello World”,这就是作业要问的内容。当我尝试在代码中添加一条print(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”行,我是否将打印代码放置在错误的位置?

Gelonida

写入文件后,您必须先将其倒回(搜索)到开头再读取

在打印语句之前添加以下行

openfile.seek(0)

seek及其参数的文档https://docs.python.org/3/library/io.html?highlight=seek#io.IOBase.seek

请注意,如果您想从同一进程(带或不带线程)中读取新编写的文件,则寻求是最好和最有效的方法

附录:(进程间方案)但是,如果要从另一个进程读取文件,则必须刷新文件或将其关闭。(如果您想继续从过程中读取文字,则最好使用冲洗。

因此,假设您有两个脚本:

script1.py

    openfile = open(filename, 'a+')
    openfile.write(newData)

    # without next line, data might not be readable
    # by another process
    openfile.flush()
    tell_script2_it_can_read_the_file()
    return

script2.py

wait_for_notification_from_script1()
with open(filename) as openfile:
    print(openfile.read())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章