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

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

问题描述

我想提示用户生成多个随机数并将其保存到文件中。他给了我们那部分。我们要做的就是打开该文件,将数字转换成列表,然后找到平均值,标准偏差等,而不使用易于构建的python工具。



我试过使用打开,但它给我无效的语法(我选择的文件名是数字,并保存到我的文档自动,所以我试过打开(数字,'r')打开(C:\\\
ame\

解决方案

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

这将给你一个你的文件中的值(字符串)的列表,带有换行符。



还可以在Windows路径名中看到您的反斜杠,因为这些也是字符串中的转义字符串。您可以使用正斜杠或双斜杠。


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.

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:\name\MyDocuments\numbers, '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.

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天全站免登陆