研究与设计分析作业(6)

it2025-11-03  2

{ "cells": [ { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "1. Write a Python program to read 5 random lines from file A and then write them to file B. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os,random\n", "os.chdir(\"C:\\\\Users\\\\tan\\\\Desktop\") " ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'C:\\\\Users\\\\tan\\\\Desktop'" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.getcwd()" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "s=[]\n", "with open('A.txt') as tasks:\n", " tasks_content=tasks.readlines()\n", " i=len(tasks_content)\n", " while(len(s)<5):\n", " x=random.randint(0,i-1)\n", " if x not in s:\n", " s.append(x)\n", "f=open('B.txt','w')\n", "for i in s:\n", " f.write(tasks_content[i])\n", "f.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "2. Ask users to enter their name and gender first. Then print it to the screen for user confirmation. After that, append the name and gender to file user_info.txt as a new line. " ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Please provide your name:tan\n", "Please provide your gender:male\n", "Please confirm your information\n", "name: tan gender: male\n", "YES OR NO?YES\n" ] } ], "source": [ "word=input('Please provide your name:')\n", "word2=input('Please provide your gender:')\n", "print(\"Please confirm your information\\nname: \"+word+\" gender: \"+word2)\n", "word3=input('YES OR NO?')\n", "if word3=='YES':\n", " f=open('C:\\\\Users\\\\tan\\\\Desktop\\\\user_info.txt','w')\n", " f.write(word+\" \"+word2)\n", " f.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.3" } }, "nbformat": 4, "nbformat_minor": 4 }
最新回复(0)