Created
November 7, 2021 12:12
-
-
Save hodunov/b889e51661a3ec2fadd1716f1821ab7c to your computer and use it in GitHub Desktop.
Homework-10 Files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Напишите функцию для создания файла и записи в него случайных чисел, | |
# каждое число записывается в файл через пробел, но не больше 10ти чисел в строку. | |
# Всего случайных чисел должно быть 1000 | |
import random | |
def create_and_write(filename): | |
with open(f"{filename}.txt", "w") as file: | |
strings = [] | |
for _ in range(100): | |
# https://docs.python.org/3/library/random.html | |
random_list = random.sample(range(100), 10) | |
# https://pythonru.com/osnovy/python-join | |
random_string = " ".join(map(str, random_list)) + '\n' | |
strings.append(random_string) | |
file.writelines(strings) | |
FILE_NAME = 'text' | |
create_and_write(FILE_NAME) | |
# Напишите другую функцию, | |
# которая считывает первый файл и возводит каждое число в квадрат. | |
# Каждое полученное число должно быть дозаписано в исходный файл в таком же формате. | |
# Добавьте по 5 тестов для каждой функции | |
def read_and_append(filename): | |
""" | |
Функция считывает файл и возводит каждое число в квадрат. | |
:param filename: имя файла без расширения, str | |
""" | |
# https://pythonworld.ru/tipy-dannyx-v-python/fajly-rabota-s-fajlami.html | |
with open(f"{filename}.txt", "r+") as file: | |
# https://pythonz.net/references/named/file.readlines/ | |
my_list = file.readlines() | |
for line in my_list: | |
result = [int(value) ** 2 for value in line.split()] | |
# https://www.digitalocean.com/community/tutorials/how-to-use-the-python-map-function-ru | |
file.write(" ".join(map(str, result)) + '\n') | |
read_and_append(FILE_NAME) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment