plapapyjh 2022-09-04 14:42 采纳率: 43.5%
浏览 51
已结题

Python初学者,在文件部分遇到的基础问题

Python初学者,在文件部分遇到的基础

"""
File: files.py
The solutions for these programs are provided, to help you get going - or to confirm that your solution was
valid.
Note: when you execute a Python program that contains a line like open('data.txt', 'w') the new file
“data.txt” is created in the same folder as the Python file in your PyCharm project.
Create a new file called files.py and do all the following separate questions in it:
Note: the intention is to give you experience using different ways to read files.
Make sure you’re confident with:
• read()
• readline()
• readlines()
• for line in file
1. Write code that asks the user for their name, then opens a file called “name.txt” and writes that name
to it.
2. Write code that opens “name.txt” and reads the name (as above) then prints,
“Your name is Bob” (or whatever the name is in the file).
3. Create a text file called numbers.txt and save it in your prac_02 directory. Put the following three
numbers on separate lines in the file and save it:
17
42
400
Write code that opens “numbers.txt”, reads only the first two numbers and adds them together then
prints the result, which should be. . . 59.
4. Now write a fourth block of code that prints the total for all lines in numbers.txt or a file with any
number of numbers.
"""

我在文件这部分学的有点迷,今天再看的时候遇到这个问题,写不下来,麻烦看一下,给个完整代码,要是有详细一些注释就太感谢了

img

  • 写回答

1条回答 默认 最新

  • EdsionWang 2022-09-04 15:12
    关注
    
    #将用户输入存到变量中
    name = input('what is your name:')
    #打开一个文件,将变量写入文件
    with open('name.txt', mode='w', encoding='utf-8') as file_obj:
        file_obj.write(name)
    
    
    
    #打开文件,后面的r是只读
    f = open('name.txt', 'r')
    #将文件中的行读出来放到变量中
    namefromfile = f.readline()
    #输出变量内容
    print('Your name is ' + namefromfile)
    #没有使用with语句块,则需要手动关闭文件
    f.close()
    
    
    
    f = open('numbers.txt', 'r')
    #把所有行读取出来
    lines = f.readlines()
    #第一行第二行装换成整数
    one = int(lines[0])
    two = int(lines[1])
    print('sum of first two lines:')
    #输出两个数的和
    print(one+two)
    f.close()
    
    
    
    f = open('numbers.txt', 'r')
    total = 0
    #for循环遍历所有行,并求和
    for line in f:
        total += int(line)
    print('total of all lines:')
    print(total)
    f.close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月12日
  • 已采纳回答 9月4日
  • 修改了问题 9月4日
  • 赞助了问题酬金10元 9月4日
  • 展开全部

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度