Split specific line in text file to x, y variables in python - 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)

Related

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

How to correctly append the output to an empty list

I am looking for words in my chosen text files.
def cash_sum(self):
with open(self.infile.name, "r") as myfile:
lines = myfile.readlines()
for line in lines:
if re.search("AMOUNT", line):
x = []
x.append(line[26:29])
print(x)
I have this output:
['100']
['100']
['100']
And I want to add them so I can have sum of all amounts from this file.
Any advices?
Initialize x outside the line-iterating loop.
Also, you don't need to readlines() separately...
def cash_sum(self):
x = []
with open(self.infile.name, "r") as myfile:
for line in myfile:
if re.search("AMOUNT", line):
x.append(line[26:29])
# or cast to int before appending:
# x.append(int(line[26:29]))
return x
This will give you the sum...
def cash_sum(self):
with open(self.infile.name, 'r') as myfile:
lines = myfile.readlines()
totalAmount = 0
for line in lines:
if re.search("AMOUNT", line):
totalAmount += float(line[26:29])
First thing I'd recommend is casting that value to a float. I say float instead of int just in case you have a decimal point. For example, float('100') == 100.0 . Once you have that, you should be able to then add them up as you would normal numbers.
You have redefined x inside your loop, so every time your loop iterates, it resets x to and empty list. Try the following:
def cash_sum(self):
with open(self.infile.name, "r") as myfile:
lines = myfile.readlines()
x = [] # That way x is defined outside the loop
for line in lines:
if re.search("AMOUNT", line):
x.append(line[26:29])
print(x)
# And if you want to add each item in the list...
num = float(0)
for number in x:
num = num + float(number)
return num

Splitting a line up into 2 different strings [duplicate]

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

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