Essays.club - Получите бесплатные рефераты, курсовые работы и научные статьи
Поиск

Контрольная работа по "Информатике"

Автор:   •  Май 3, 2024  •  Контрольная работа  •  1,065 Слов (5 Страниц)  •  55 Просмотры

Страница 1 из 5

 Задание: Создание, чтение и запись файлов в Python

  1. Создайте текстовый файл с именем "example.txt" в текущей директории и запишите в него несколько строк текста.

with open("example.txt", "w") as exp_file:

    exp_file.write("Hello world \n")

    exp_file.write("I hope you're doing well today \n")

    exp_file.write("This is a text file \n")

    exp_file.write("Have a nice time \n")

[pic 1]

  1. Откройте файл "example.txt" в режиме чтения и выведите его содержимое на экран.

with open("example.txt") as example_file:

    print(example_file.read())[pic 2]

  1. Запросите у пользователя ввод нового текста и добавьте его в конец файла "example.txt".

file_name = "example.txt"

user_inputs = []

line_count = 1

print("Enter your text below: ('quite' keyword to exit)")

while True:

    user_input = input(f"{line_count}:")

    if user_input == 'quite':

        print(f"{line_count-1} line of text will append to {file_name}.")

        break

    line_count += 1

    user_inputs.append(user_input+"\n")

with open(file_name, "a") as example_file:

    for user_input in user_inputs:

        example_file.write(user_input)

[pic 3]

  1. Закройте файл "example.txt".

  1. Откройте файл "example.txt" в режиме чтения и выведите его содержимое на экран, чтобы убедиться, что новый текст был успешно добавлен в файл.

file = open("example.txt")

try:

    print(file.read())

finally:

    file.close()

[pic 4]

  1. Создайте новый текстовый файл с именем "copy_example.txt".

with open("copy_example.txt", "x") as new_file:

    print("New copy_example.txt file was created successfully!")

[pic 5]

  1. Скопируйте содержимое файла "example.txt" в файл "copy_example.txt".

with open("example.txt", "r") as example_file, open("copy_example.txt", "w") as copy_file:

    print(copy_file.write(example_file.read()))

  1. Закройте оба файла.
  2. Откройте файл "copy_example.txt" в режиме чтения и выведите его содержимое на экран, чтобы убедиться, что содержимое файлов идентично.

with open("example.txt", "r") as first_file, open("copy_example.txt", "r") as second_file:

    # print("FIRST FILE:\n"+first_file.read())

    # print("SECOND FILE:\n"+second_file.read())

    # OR

    print("TWO FILES ARE "+"EQUAL" if first_file.read()

          == second_file.read() else "NOT EQUAL")

[pic 6]

  1. Удалите файлы "example.txt" и "copy_example.txt" из текущей директории.

import os

delete_files = ["example.txt", "copy_example.txt"]

for file in delete_files:

    if os.path.exists(file):

        os.remove(file)

    else:

        print(f"The {file} does not exist")

...

Скачать:   txt (11.1 Kb)   pdf (277.2 Kb)   docx (352.2 Kb)  
Продолжить читать еще 4 страниц(ы) »
Доступно только на Essays.club