试图读取文件时,实际文件包含正确的文本,.read()不显示任何内容:

2024-09-30 22:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

这个创建的文本文件包含两个单词“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”,我是否将打印代码放在了错误的位置


Tags: theto代码testhelloworldreadopen
3条回答
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
    with open(filename, 'a+') as file:
        file.write(newData)
    with open(filename, 'r') as file:
        return file.read()

# expected output: Hello World
with open("test.txt", 'w') as f: 
    f.write("Hello ")
appendAndPrint("test.txt", "World")

写入文件后,需要将其关闭.close()。然后用open('test.txt', 'r+)再次打开它

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)
    openfile.close()

    openfile = open(filename, 'r+')
    print(openfile.read())


with open("test.txt", 'w') as f: 
    f.write("Hello ")
    f.close()

appendAndPrint("test.txt", "World")  # expected output: Hello World

写入文件后,必须倒带(查找) 在阅读之前,把它放回到开头

在print语句之前添加以下行

openfile.seek(0)

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

请注意,如果要从同一进程(有线程或无线程)中读取新写入的文件,seek是最好、最有效的方法

附录:(进程间场景) 但是,如果要从另一个进程读取该文件,则必须刷新该文件或将其关闭。(如果您想继续在流程中读写,则首选刷新方式

假设您有两个脚本:

脚本1.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

脚本2.py

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

相关问题 更多 >