Splitting a line up into 2 different strings [duplicate] - python

This question already has answers here:
Split string on whitespace in Python [duplicate]
(4 answers)
Closed 4 years ago.
So I have a file where a bunch of coordinates are in. But one x has its y value in the same line just seperated by a space. How do I split each line into two seperated pieces up so that I get the y and the x coord seperate(eg in a strig array)?
Coordinate example:
934 100

Simply use line.split() for each string line.
It also works on lines with more than two coordinates.
Examples:
line = "934 100",
x, y = line.split(), print(x,y) = 934 100
line = "1 61 298 3333 ", a, b, c, d = line.split(), print(a,b,c,d) = 1 61 298 3333

Use split method to split the line default delimeter is space
with open("file") as f:
for line in f.readlines():
line=line.strip().split()
x=line[0]
y=line[1]

Write as you say it - split the line on whitespace:
line = "934 100"
x, y = line.split()

with open(filename, "r") as fd:
lines_list = fd.readlines()
for index in range(len(lines_list)):
x, y = lines_list[index].split(' ')
print(x, y)
open file in read mode i.e "r"
with open(filename, "r") as fd:
Using readlines() we will get all the data of file in form of list of lines
lines_list = fd.readlines()
For each line split the line using space as delimiter and assign to x and y variables
x, y = lines_list[index].split(' ')

Use split()
List compression way of doing this is:
//suppose your input is 10 22
c=[int(temp) for i in input().split()]
//it will give us a list with elements [10, 22]
print(c) //[10, 22]
If you are reading from the file:
with open(file_path , "r") as file:
lines_list = file.readlines()
for index in range(len(lines_list)):
x, y = lines_list[index].split(' ')
print(x, y)
If you have it as a string:
s = “10 22”
x, y=s.split()
print(x, y) //10 22

Related

Split specific line in text file to x, y variables in python

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)

Why is my code writing something twice while reading a file

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())

Separating values from text file in python

I am trying to read in a text file with the following data:
362 147
422 32
145 45
312 57
35 421
361 275
and I want to separate the values into pairs so 362 and 147 would be pair 1, 422 and 32 pair 2 and so on.
However I run into a problem during the 5 pair which should be 35,421 but for some reason my code does not split this pair correctly, i think this is because of the spaces since only this pair has a two digit number and then a 3 digit number. But I'm not sure how to fix this, here's my code:
def __init__(filename):
f = open(filename, "r") #reads file
#print (f.read) # test if file was actually read
f1 = f.readlines() # reads individual lines
counter = 0
for line in f1:
values = line.split(" ") #splits the two values for each line into an array
value1 = values[0].strip() #.strip removes spaces at each values
value2 = values[1].strip()
counter = counter + 1
print('\npair: {}'.format(counter))
#print(values)
print(value1)
print(value2)
The output I get:
pair: 1
362
147
pair: 2
422
32
pair: 3
145
45
pair: 4
312
57
pair: 5
35
pair: 6
361
275
Try this :
def __init__(filename):
with open(filename, "r") as f:
lines = [i.strip() for i in f.readlines()]
for line_num, line in enumerate(lines):
p1, p2 = [i for i in line.split() if i]
print(f"pair: {line_num+1}\n{p1}\n{p2}\n\n")
Note : Always try to use with open(). In this way python takes care of closing the file automatically at the end.
The problem with your code is that you're not checking whether the words extracted after splitting values are empty string or not. If you print values for each line, for the pair 5, you'ld notice it is ['', '35', '421\n']. The first value of this one is an empty string. You can change your code to this :
def __init__(filename):
f = open(filename, "r") #reads file
#print (f.read) # test if file was actually read
f1 = f.readlines() # reads individual lines
counter = 0
for line in f1:
values = line.split() #splits the two values for each line into an array; Addendum .split(" ") is equivalent to .split()
values = [i for i in values if i] #Removes the empty strings
value1 = values[0].strip() #.strip removes spaces at each values
value2 = values[1].strip()
counter = counter + 1
print('\npair: {}'.format(counter))
#print(values)
print(value1)
print(value2)
Change this line:
values = line.split(" ")
to:
values = line.split()

Read file line by line and create lists

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

Python: How to read a text file containing co-ordinates in row-column format into x-y co-ordinate arrays?

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)

Categories