При попытке прочитать файл, фактический файл имеет правильный текст, .read () ничего не показывает: - PullRequest
1 голос
/ 21 июня 2020

В создаваемом текстовом файле есть слова "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» с этим оператором, поместил ли я напечатать код не в том месте?

Ответы [ 3 ]

2 голосов
/ 21 июня 2020

После записи в файл вы должны перемотать (искать) его обратно в начало перед чтением

добавить следующую строку перед оператором печати

openfile.seek(0)

Документация поиска и его параметров https://docs.python.org/3/library/io.html?highlight=seek#io .IOBase.seek

Обратите внимание, что поиск - лучший и наиболее эффективный способ, если вы хотите читать только что записанный файл из того же процесса (с потоками или без )

Дополнение: (Межпроцессный сценарий) Однако, если вы хотели прочитать файл из другого процесса, вам нужно было sh проверить файл или закрыть его. (очистка будет предпочтительнее, если вы хотите продолжить чтение записи изнутри процесса.

Итак, представьте, что у вас есть два скрипта:

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())
0 голосов
/ 21 июня 2020

После записи в файл нужно закрыть его .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

0 голосов
/ 21 июня 2020
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")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...