你如何在 Python 中将文件读入列表? [英] How do you read a file into a list in Python?

查看:32
本文介绍了你如何在 Python 中将文件读入列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提示用户生成一些随机数并将其保存到文件中.他给了我们那部分.我们要做的部分是打开该文件,将数字转换为列表,然后在不使用简单的内置 Python 工具的情况下找到均值、标准差等.

I want to prompt a user for a number of random numbers to be generated and saved to a file. He gave us that part. The part we have to do is to open that file, convert the numbers into a list, then find the mean, standard deviation, etc. without using the easy built-in Python tools.

我试过使用 open 但它给了我无效的语法(我选择的文件名是数字",它自动保存到 我的文档",所以我尝试了 open(numbers, 'r')open(C: ameMyDocuments umbers, 'r') 并且都没有成功.

I've tried using open but it gives me invalid syntax (the file name I chose was "numbers" and it saved into "My Documents" automatically, so I tried open(numbers, 'r') and open(C: ameMyDocuments umbers, 'r') and neither one worked).

推荐答案

with open('C:/path/numbers.txt') as f:
    lines = f.read().splitlines()

这将为您提供文件中的值(字符串)列表,并删除换行符.

this will give you a list of values (strings) you had in your file, with newlines stripped.

此外,请注意 Windows 路径名中的反斜杠,因为它们也是字符串中的转义字符.您可以改用正斜杠或双反斜杠.

also, watch your backslashes in windows path names, as those are also escape chars in strings. You can use forward slashes or double backslashes instead.

这篇关于你如何在 Python 中将文件读入列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆