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日
  • 展开全部

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮