Read txt file and put in list with python - python

I have a file with text with only 0's and 1's. No space between them. Example:
0101110
1110111
I would like to read a character at a time and place them as a single element in a list of integers.
My code:
intlist = []
with open('arq.txt', 'r') as handle:
for line in handle:
if not line.strip():
continue
values = map(int, line.split())
intlist.append(values)
print intlist
handle.close()
My result:
[[101110], [1110111]]
Like if I transform the 0101110 in intlist = [0,1,0,1,1,1,0,1,1,1,0,1,1,1]. (without '\n')

You just need two changes. The first is, when you're making values, you need to take each individual character of the line, instead of the entire line at once:
values = [int(x) for x in line.strip() if x]
Now, if you run this code on its own, you'll get [[1, 0, ...], [1, 1, ...]]. The issue is that if you call list.append with another list as an argument, you'll just add the list as an element. You're looking for the list.extend method instead:
intlist.extend(values)
Your final code would be:
intlist = []
with open('arq.txt', 'r') as handle:
for line in handle:
if not line.strip():
continue
values = [int(x) for x in line.strip() if x]
intlist.extend(values)
print intlist

If all you have is numbers and linefeeds, you can just read the file, remove the linefeeds, map the resulting string to integers, and turn that into a list:
with open('arq.txt') as handle:
intlist = list(map(int, handle.read().replace('\n', '')))
print intlist

Here's one way you can do it. You also don't need to use handle.close() the context manager handles closing the file for you.
intlist = []
with open('arq.txt', 'r') as handle:
for line in handle:
if not line.strip():
continue
intlist[:] += [int(char) for i in line.split() for char in i]
print(intlist)

Use strip() for delete \n and filter with bool for deleting empty strings:
with open('test.txt') as f:
lines = map(lambda x: x.strip(), filter(bool, f))
print [int(value) for number in lines for value in number]

One possibility:
intlist = []
with open('arq.txt', 'r') as handle:
for line in handle:
for ch in line.strip():
intlist.append (ch)
print intlist

Related

I am trying to read in a file and then return a list of int values using the .readlines()

For a school assignment
we want to convert every item in the list to be an int using the int(val) function. This will involve first reading in the file, loading all the lines, and then looping through all lines building a second list of ints (use lst). You should return the list of ints
but I don't know how to do it.
This is what I have so far.
def file_int_list(file):
with open(file, 'r+') as f:
lst = []
lines = f.readlines()
for rows in lines:
lst.append(rows)
return lst
lst = []
lines = f.readlines()
for rows in lines:
lst.extend(list(map(int, rows.split(' '))))
return lst

Python: Write float array to a file

What is the cleanest and easiest way to write float array to a file?
This is what i was trying to do. mylist is array.
match = re.search(r"DeltaE =\s+(\S+).* Intensity =\s+(\S+)", line)
if match is not None:
self.deltae = float(match.group(1))
self.intensity = float(match.group(2))
mylist = [self.deltae, self.intensity]
with open("Test.txt", 'w') as myfile:
for range(sublist) in mylist:
myfile.write(', '.join(str(item) for item in sublist)+'\n')
print(mylist)
My list looks like that :
13.5423 0.0116934333
17.9918 0.0476088508
22.4523 0.0082869379
26.5963 0.00291399
34.1077 0.0222519629
39.0881 0.0027373305
Assuming that mylist is a 2-element list, you can use a generator expression:
with open("Test.txt", 'a') as myfile:
myfile.write(', '.join(str(item) for item in mylist)+'\n')
or the outdated map to map float to str:
with open("Test.txt", 'a') as myfile:
myfile.write(', '.join(map(str, mylist))+'\n')
If mylist is defined inside a loop, then you need to run this code inside the same loop to process all rows.

How to convert a 2x2 map to a list of lists?

Python
How do I turn a grid of:
x,x
x,x
to a list of lists?:
[['x', 'x'], ['x', 'x']]
It's as simple as:
with open(...) as f:
list_of_lists = [line.strip().split(",") for line in f]
# use list_of_lists
Make a function to go through each line and split them by the commas.
def get_gridas_list(filename):
# an empty list to store your data
grid_list = []
# with is the safest way to open a text document
with open(filename, 'r') as file:
# iterate through all the lines in the file
for line in file:
#split is a function associated with strings
# "x,x".split(',') -> ['x', 'x']
grid_list.append(line.strip().split(','))
# return the now full list of lists
return grid_list
Use readline from file and then the split-method
list = []
line_from_file = '23wda, wa0dw'
parts = line_from_file.split(', ')
list.append([parts[0], parts[1]])
line_from_file = '234f4fda, wa03d2dw'
parts = line_from_file.split(', ')
list.append([parts[0], parts[1]])
print(list)
Here's a method to get a list of lists:
gridlist = []
f = open('**path/to/file/here**')
for line in f:
a = line.strip().split(',')
gridlist.append(a)
print gridlist

Building a List from a text file in python

I am a python newbie.
I want to read a text file which reads something like this
1345..
245..
..456
and store it in a list of lists of integers. I want to keep the numbers and replaces the periods by 0s.How do i do it?
EDIT:
Apologize for the ambiguous output spec
p.s I want the output to be a list of list
[ [1,3,4,5,0,0],
[2,4,5,0,0],
[0,0,4,5,6]]
with open('yourfile') as f:
lst = [ map(int,x.replace('.','0')) for x in f ]
Which is the same thing as the following nested list-comp:
lst = [ [int(val) for val in line.replace('.','0')] for line in f]
Here I used str.replace to change the '.' to '0' before converting to an integer.
with open(file) as f:
lis=[[int(y) for y in x.replace('.','0').strip()] for x in f]
Here's an answer in the form of classic for loops, which is easier for a newbie to understand:
a_list = []
l = []
with open('a') as f:
for line in f:
for c in line.rstrip('\n').replace('.', '0'):
l.append(int(c))
a_list.append(l)
#next line
l = []
print a_list

Python - read numbers from text file and put into list

So like the title says im starting to learn some python and im having trouble picking up on this technique. What I need to accomplish is to read in some numbers and store them in a list. The text file looks like the following:
0 0 3 50
50 100 4 20
Basically these are coordinates and directions to be used for python's turtle to make shapes. I got that part down the only problem is getting them in a correct format. So what I can not figure out is how to get those numbers from the file into [ [0, 0, 3, 50], [50, 100, 4, 20] ]
A list, with each four coordinates being a list in that one big list.
Heres my attempt but it as I said I need some help - thank you.
polyShape=[]
infile = open(name,"r")
num = int(infile.readline(2))
while num != "":
polyShape.append(num)
num = int(infile.readline(2))
infile.close()
with open('data.txt') as f:
polyShape = []
for line in f:
line = line.split() # to deal with blank
if line: # lines (ie skip them)
line = [int(i) for i in line]
polyShape.append(line)
will give you
[[0, 0, 3, 50], [50, 100, 4, 20]]
This will work with a file that contains blank lines (or not).
Using the with construct will close the file for you automatically when you are done, or an exception is encountered.
Assuming there isn't actually a blank line in your input file:
with open(name, "r") as infile:
polyShape = [map(int, line.split()) for line in infile]
Explanation: map(int, line.split()) splits each line and converts each part to an int. The [X for Y in Z] construct is a list comprehension that in turn maps the map over all lines of the file and returns its results in a list.
If you find this too complicated for now, then the map(int, line.split()) is the main take-home message.
with open('data.txt') as f:
lis=[map(int,x.split()) for x in f if x.strip()] # if x.strip() to skip blank lines
#use list(map(int,x.split())) in case of python 3.x
this is how map() works:
>>> map(int,'1 2 3 4'.split())
[1, 2, 3, 4]
One-liner:
[ [int(x) for x in line.split(' ')] for line in open(name,'r').readlines() if line.strip()]
but the readlines part is probably not a great idea.
I'm quite sure that [int(x) for x in ... ] is faster than using map as in other suggested solutions.
Edit
Thanks to Blender : no need for .readlines, which is cool, so we just have :
[ map(int, line.split()) for line in open(name,'r') if line.strip()]
I also used map(int, ) because it's actually faster, and also you can use just line.split() instead of line.split(' ').
Iterating over the file would be the easiest way:
poly_shape = []
with open(name, 'r') as handle:
for line in handle:
if not line.strip():
continue # This skips blank lines
values = map(int, line.split())
poly_shape.append(values)
I do not recommend using append for a big array. It's 50 time slower than creating a zero array and assigning values to it.
import numpy
fname = "D:\Test.txt";
num_lines = sum(1 for line in open(fname));
array = numpy.zeros((num_lines,4));
k = 0;
with open(fname, "r") as ins:
for line in ins:
a =[int(i) for i in line.split(' ')];;
array[k,0:4] =a;
k = k+1;
print(array)

Categories