简体   繁体   中英

Read text file into array using python

I have a textfile newfile.txt which contains following info:

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

how should i read this file using python such that

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.

such that:

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

var1 should be equal to http://filefirst.txt

How should I go about doing this?

I am writing python script like this:

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]. Currently what is happening it is storing only last line of txt file.

How can i modify the code above according to my requirements.

Regards 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.

Also, while Kevin's answer is OK, he doesn't close the file. The beauty of the with open is that it closes it automatically as soon as it's done reading it.

Here is one way to read the file into an array:

Assume that you have the following in a file named 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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