Paul Zaruba
Paul Zaruba

Reputation: 23

Passing text file data to a variable

I am learning python and am having a bit of trouble with utilizing data in a text file.

As an example the text file is structured line by line like this:

name 656 334

I want to grab the data in a loop line by line and put the two integers into two separate variables like a = 656 b = 334 but I’m having trouble getting it to do that. I’ve tried various iterations of lists and numpy arrays but at most I can only get it to include both numbers together when I call on the array.

Any help would be much appreciated.

Upvotes: 2

Views: 1182

Answers (6)

Trenton McKinney
Trenton McKinney

Reputation: 62513

import pandas as pd

df = pd.read_csv('data.csv', sep=' ', header=None)
df['function_solution'] = df[1].multiply(df[2])
  1. Iterating through data is inefficient
  2. Using a pandas.DataFrame, which uses vectorized operations is more efficient
  3. pd.DataFrame.multiply is just an example. Once your data is in the DataFrame, any function can be performed.

Upvotes: 0

SUN
SUN

Reputation: 189

You can try using Pandas as well. I have used below code with my rating txt.

# import pandas library
import pandas as pd
# read rating file, without header and set column name for fields
rating_df = pd.read_csv('ratings.txt', sep=' ', header=None, names =["userId", "itemId", "rating"])

for index, row in rating_df.iterrows():
    print(int(row['userId']), int(row['itemId']))

Upvotes: 0

inostia
inostia

Reputation: 8023

If you know that all of the values in each line will be separated by spaces, then you can iterate through the lines in the file and use split to get the values into a list, then assign them accordingly.

with open('my_file.txt') as my_file:
    for line in my_file.readlines():
        parts = line.split()
        a = parts[1]
        b = parts[2]  # or parse it as _, a, b = line.split() as lennhv said above

Upvotes: 1

Turtalicious
Turtalicious

Reputation: 430

Run through the whole file line by line and split each line at the spaces. Something like this:

with open("your filename", "r") as f:
    lines = f.readlines()
    for line in lines:
        name, a, b = line.split()

        #Do anything with the values here

This can also be done with a shorter list comprehension, but since you're starting off that should do it.

Upvotes: 0

lennhv
lennhv

Reputation: 103

Assuming your data line format is the same in whole document and the data separator is an space, you could unpack the line data with split like this:

_, a, b, = line.split()

Upvotes: 2

Andreu Gallofré
Andreu Gallofré

Reputation: 1673

You can use a regex to extract the numbers into an array

Example code here:

import re

txt = "name 656 334"
x = re.findall("[0-9]+", txt)
print(x)

This will return an array with the two values

['656', '334']

Then you just have to access both values of the array and assign it into a variable or use it just by accessing the array

Upvotes: 0

Related Questions