简体   繁体   English

使用python将文本文件读入数组

[英]Read text file into array using python

I have a textfile newfile.txt which contains following info: 我有一个textfile newfile.txt,其中包含以下信息:

http://filefirst.txt
http://filesecond.txt
http://filethird.txt

how should i read this file using python such that 我应该如何使用python读取此文件

line[0] = http://filefirst.txt
line[1] = http://filesecond.txt
...

and so on also i want to read this array variable in android activity using intents and bundle. 依此类推,我想在Android活动中使用intents和bundle读取这个数组变量。

such that: 这样:

bundle = getIntent().getExtras();
var1 = bundle.tostring();

var1 should be equal to http://filefirst.txt var1应该等于http://filefirst.txt

How should I go about doing this? 我该怎么做呢?

I am writing python script like this: 我正在写这样的python脚本:

f = open('newfile.txt')
for line in iter(f):
    extravalue = {}
    extravalue['URIVALUE']=line
    print(line)
    print("value")
    MonkeyRunner.sleep(10)
device.startActivity(component=runComponent, extras=extravalue)
device.touch(10,350, 'DOWN_AND_UP')
f.close()

now i want to read extras in another activity. 现在我想在另一个活动中阅读额外内容。 I am doing it like this: 我是这样做的:

Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String uri = null;

        if (bundle != null && (uri = bundle.getString("URIVALUE")) != null)
        String[] path = uri.split(",");

In android i want to read such that path[0]=line[0],path[1]=line[1]. 在android中我想读取路径[0] =行[0],路径[1] =行[1]。 Currently what is happening it is storing only last line of txt file. 目前正在发生的事情是它只存储txt文件的最后一行。

How can i modify the code above according to my requirements. 如何根据我的要求修改上面的代码。

Regards Mayank 关心Mayank

This is the answer to the first part: 这是第一部分的答案:

with open('newfile.txt') as f:
    line = f.readlines()

I don't know what you mean by the second part, nor what getIntent does. 我不知道第二部分是什么意思,也不知道getIntent是什么意思。

Also, while Kevin's answer is OK, he doesn't close the file. 此外,虽然Kevin的答案还可以,但他没有关闭文件。 The beauty of the with open is that it closes it automatically as soon as it's done reading it. with open的美妙之处在于它一读完就自动关闭它。

Here is one way to read the file into an array: 以下是将文件读入数组的一种方法:

Assume that you have the following in a file named data.txt: 假设您在名为data.txt的文件中包含以下内容:

http://filefirst.txt
http://filesecond.txt
http://filethird.txt

This code will put it into an array: 这段代码会把它放到一个数组中:

f = open("data.txt")
lines = f.readlines()
print lines

Output: 输出:

['http://filefirst.txt\n', 'http://filesecond.txt\n', 'http://filethird.txt\n', '\n']

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

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