I have a file which contains lines of the form
2.484 5.234
6.123 1.461
1.400 9.381
I would like to read these into python lists x containing the first value of each line and y containing the second value of each line.
How can I achieve this? Here is my attempt:
x = []
y = []
with open(filename) as file_:
for line in file_:
a, b = line
x.append(a)
y.append(b)
a, b = line
cannot work because you're trying to unpack a string into 2 elements (unless the string itself is 2 elements long, which isn't the case)
you want to convert to float & unpack the splitted line like this:
a, b = map(float,line.split())
in that case split() without arguments takes care of multiple spaces, linefeeds, tabs... like awk would do so it's pretty easy.
You can try this:
data =[map(float, i.strip('\n').split()) for i in open('filename.txt')]
You can do that
x = []
y = []
with open("file.txt", "r") as ins:
for line in ins:
elt = line.split()
x.append(elt[0])
y.append(elt[1])
print x
print y
Related
I have made a code in python that read text file (Test.text), the text file contains data like in below
10 20
15 90
22 89
12 33
I can read specific line by use this code
particular_line = linecache.getline('Test.txt', 1)
print(particular_line)
I tried to use code to split the text file to x, y value but it got all lines not the specific line that I need
with open('Test.txt') as f:
x,y = [], []
for l in f:
row = l.split()
x.append(row[0])
y.append(row[1])
So how to get specific line and split it to two values x and y
You might do
particular_line = linecache.getline('Test.txt', 1)
print(particular_line)
x, y = particular_line.split()
print(x) # 10
print(y) # 20
.split() does give list with 2 elements, I used so called unpacking to get 1st element into variable x and 2nd into y.
You are missing the readlines in your code
with open('Test.txt') as f:
x,y = [], []
for l in f.readlines():
row = l.split()
x.append(row[0])
y.append(row[1])
import pandas as pd
xy = pd.read_csv("Test.txt", sep=" ", header=None).rename(columns={0:"x", 1:"y"})
Now you can access to all x and y values with xy.x.values and xy.y.values.
Note that I chose sep=" " as separator becose I suppose that your x and y are separated by a single space in you file.
This is a rather condensed example:
with open("input.txt", "r") as f:
data = f.read()
# Puts data into array line by line, then word by word
words = [y.split() for y in data.split("\n")]
# Gets first word (x)
x = [x[0] for x in words]
# Gets second word (y)
y = [x[1] for x in words]
Where [y.split() for y in data.split("\n")] gets each line by splitting at \n and splits the x and y values (.split()) by the space in-between them
To get the specific line you can use this code
with open('Test.txt') as f:
particular_line = f.readlines()[1]
print(particular_line)
Notice the index inside [], it starts from 0 as same as most other languages. For example, if you want to get the first line, you'd change it to 0.
By parsing it into two variables you can use
x, y = particular_line.split()
print(x)
print(y)
So, put them together,
with open('Test.txt') as f:
particular_line = f.readlines()[1]
print(particular_line)
x, y = particular_line.split()
print(x)
print(y)
You might also need it in a function format,
def get_particular_line_to_x_y(filename, line_number):
with open(filename) as f:
particular_line = f.readlines()[line_number]
return particular_line.split()
if __name__ == '__main__':
x, y = get_particular_line_to_x_y('Test.txt', 0)
print(x)
print(y)
I'm working on a code that sends mails to the persons given in the text file.
This is the text file:
X,y#gmail.com
Z,v#gmail.com
This is my code:
with open("mail_list.txt","r",encoding ="utf-8") as file:
a = file.read()
b = a.split("\n")
d = []
for i in b:
c = i.split(",")
d.append(c)
for x in d:
for y in x:
print(x[0])
print(x[1])
The output should be:
X
y#gmail.com
Z
v#gmail.com
But instead it is:
X
y#gmail.com
X
y#gmail.com
Z
v#gmail.com
Z
v#gmail.com
Why is that?
How can I fix it?
You're iterating over the columns in every row, but not using the column value:
for x in d:
for y in x:
print(y)
Please have a look on this solution. I believe this is more elegant and efficient than the current one. Don't just rely on line break splitting. Instead get all the data in form of lines already split by \n(line break) and then use the content as per your requirements.
lines = []
with open('mail_list.txt') as f:
lines = f.readlines()
for line in lines:
info = line.split(',')
print(info[0])
print(info[1])
You need to only iterate on list d.
with open("mail_list.txt", "r", encoding ="utf-8") as file:
a = file.read()
b = a.split("\n")
d = []
for i in b:
c = i.split(",")
d.append(c)
for x in d:
print(x[0])
print(x[1])
To make it simpler, you can read your file line by line and process it at the same time. The strip() method removes any leading (spaces at the beginning) and trailing (spaces or EOL at the end) characters.
with open("mail_list.txt", "r", encoding ="utf-8") as file:
for line in file:
line_s = line.split(",")
print(line_s[0])
print(line_s[1].strip())
I have a text file with the following information.
document.txt:
z
-0.01,0.04,-0.04,0,-0.06,-0.08,0.04,0.03
z
0.1,-0.02,0.1,0.14,0.07,0.05,0.01
z
0.05,0.05,0.12,0.13,0.08,0.01,0.12,0.11
Essentially, I want my python program to extract the numbers between the markers z and add it to a list. So there will be 3 lists, the first will contain the numbers between the first and second z, the second list will contain the numbers between the second and third z etc...
Here is what I have so far that takes all the numbers, converts them to floats and puts it in a list. Now I need to split it into lists that only contain the numbers between the marker, z.
f = open(file_name)
contents = f.readlines()
myList = []
for line in contents:
line = line.split()
if 'z' not in line:
for j in line:
j = j.split(',')
for l in j:
l = float(l)
myList.append(l)
You can set the document.txt in a string and split it on "z". You get a list where each row is a value from that list. So you can make strings from that list and then split it again on ",". That should do the trick
#open text file in read mode
text_file = open("document.txt", "r")
#read whole file to a string
data = text_file.read()
#close file
text_file.close()
#split the string
data.split("z")
#remove the first empty value of the list
del data[0]
#since you wanted it in 3 separate list
l1 = data[0]
l2 = data[1]
l3 = data[2]
#split the other 3 lists now and done
l1.split(",")
l2.split(",")
l3.split(",")
this gives you the list you wanted.
I'm trying to take a file that have and take whatever number is on line one (and two and three, etc.) and assign them to a given variable. So say my file is just like:
1
5
6
1
So then how would I take line one and assign that value to variable_a within my code, then take line two and assign it to variable_b. Thanks!
with open(fname) as f:
content = f.readlines()
numbers = [int(x) for x in content]
Try this:
import string
fi = open(fname, "r")
vars = fi.read()
fi.close()
pos = 0
for i in vars.split("\n"):
exec('variable_' + string.lowercase[pos] + '=' + i)
pos += 1
print(variable_b) # will print 5
I have a text file with numbers stored in the following format:
1.2378 4.5645
6.789 9.01234
123.43434 -121.0212
... and so on.
I wish to read these values into two arrays, one for x co-ordinates and the other for y co-ordinates. Like, so
x[0] = 1.2378
y[0] = 4.5645
x[1] = 6.789
y[1] = 9.01234
... and so on.
How should I go about reading the text file and storing values?
One method:
x,y = [], []
for l in f:
row = l.split()
x.append(row[0])
y.append(row[1])
where f is the file object (from open() for instance)
You could also use the csv library
import csv
with open('filename','r') as f:
reader = csv.reader(f,delimeter=' ')
for row in reader:
x.append(row[0])
y.append(row[1])
And you can also use zip to make it more succinct (though possibly less readable:
x,y = zip(*[l.split() for l in f])
where f is the file object, or
import csv
x,y = zip(*csv.reader(f,delimeter=' '))
again where f is the file object. Not that the last two methods will load the entire file into memory (although if you are using python 3 you can use generator expressions and avoid that).
Read it per lines, and split it using split:
with open('f.txt') as f:
for line in f:
x, y = line.split()
#do something meaningful with x and y
Or if you don't mind with storing the whole list to your computer's memory:
with open('f.txt') as f:
coordinates = [(c for c in line.split()) for line in f]
And if you want to store the xs and ys in separate variables:
xes = []
ys = []
with open('f.txt') as f:
for line in f:
x, y = line.split()
xes.append(x)
ys.append(y)