简体   繁体   English

什么是在python中导入文本文件的快速方法?

[英]what is a quick way to import a text file in python?

I have a plain text file with a sequence of numbers, one on each line. 我有一个带有一系列数字的纯文本文件,每行一个。 I need to import those values into a list. 我需要将这些值导入列表。 I'm currently learning python and I'm not sure of which is a fast or even "standard" way of doing this (also, I come from R so I'm used to the scan or readLines functions that makes this task a breeze). 我目前正在学习python而且我不确定这是一种快速甚至是“标准”的方式(同样,我来自R所以我习惯了scanreadLines函数,这使得这项任务变得轻而易举)。

The file looks like this (note: this isn't a csv file, commas are decimal points): 该文件看起来像这样(注意:这不是csv文件,逗号是小数点):

204,00
10,00
10,00
10,00
10,00
11,00
70,00
276,00
58,00
...

Since it uses commas instead of '.' 因为它使用逗号而不是'。' for decimal points, I guess the task's a little harder, but it should be more or less the same, right? 对于小数点,我猜任务有点难,但它应该或多或少相同,对吧?

This is my current solution, which I find quite cumbersome: 这是我目前的解决方案,我发现这很麻烦:

f = open("some_file", "r")
data = f.read().replace('\n', '|')
data = data[0:(len(data) - 2)].replace(',', '.')
data = data.split('|')
x = range(len(data))
for i in range(len(data)):
    x[i] = float(data[i])

Thanks in advance. 提前致谢。

UPDATE UPDATE

I didn't realize the comma was the decimal separator. 我没有意识到逗号是小数点分隔符。 If the locale is set right, something like this should work 如果区域设置设置正确,这样的事情应该有效

lines = [locale.atof(line.strip()) for line in open(filename)]

if not, you could do 如果没有,你可以做到

lines = [float(line.strip().replace(',','.')) for line in open(filename)]

lines = [line.strip() for line in open(filename)]

if you want the data as numbers ... 如果你想把数据作为数字......

lines = [map(float,line.strip().split(',')) for line in open(filename)]
  • edited as per first two comments below 根据以下前两条评论编辑

bsoist's answer is good if locale is set correctly. 如果正确设置了区域设置,那么bsoist的答案很好。 If not, you can simply read the entire file in and split on the line breaks ( \\n ), then use a list comprehension for replacements. 如果没有,您可以简单地读取整个文件并在换行符上拆分( \\n ),然后使用列表推导替换。

with open('some_file.txt', 'r') as datafile:
    data = datafile.read()

x = [float(value.replace(",", ".")) for value in data.split('\n')]

For a more simpler way you could just do 您可以采用更简单的方式

Read = []
with open('File.txt', 'r') as File:
    Read = File.readLines()

for A in Read:
    print A

The "with open()" will open the file and quit when it's finished reading. “with open()”将打开文件,并在完成阅读后退出。 This is good practice IIRC. 这是IIRC的良好做法。

Then the For loop will just loop over Read and print out the lines. 然后For循环将循环读取并打印出行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM