-1

I am trying to know how to assign certain variables from the text files per line in Python.

Text file:

0 Longoria Julia Manager
1 Valdivia Corina Surgeon

In the C++ version, the code to assign each variable per line is coded like this:

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int ID[2];
string lName[2];
string fName[2];
string jobTitle[2];

int main()
{
  fstream file;
  file.open("Employee List.txt");
  index = 0;
  while (!file.eof())
  {
    file >> ID[index] >> lName[index] >> fName[index] >> jobTitle[index];
    index++;
  }
  file.close();
  return 0;
}

In the Java version, the code to assign each variable per line is coded like this:

import java.io.*;
import java.util.*;

public class fileToVariable
{
  public static void main(String[] args)
  {
    int ID[2] = {0, 0};
    String lName[2] = {"", ""};
    String fName[2] = {"", ""};
    String jobTitle[2] = {"", ""};
    try
    {
      ifstream = new Scanner(new fileInputStream("Employee List.txt"));
    }
    catch (FileNotFoundException e)
    {

    }
    while (ifstream.hasNextLine())
    {
      ID[index] = ifstream.nextInt();
      lName[index] = ifstream.next();
      fName[index] = ifstream.next();
      jobTitle[index] = ifstream.next();
      index++;
    }
  }

Does anyone know how the Python equivalent to assigning each variables from the file is coded?

Biffen
  • 5,354
  • 5
  • 27
  • 32
  • 1
    Not related to Python, but [Why `while (!file.eof())` is wrong in C++](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Barmar Apr 21 '18 at 18:53

2 Answers2

0

Python doesn't have any built-in methods for reading words directly into variables. Instead, you read the whole line into a string, then use string operations to parse it.

And rather than having separate lists for each attribute, we would normally collect them all into a dictionary, and then make a list of these.

employees = []
line = f.readline()
id, lname, fname, jobtitle = line.split()
employees.append({"id": id, "fname": fname, "lname": lname, "title": jobtitle})
Barmar
  • 596,455
  • 48
  • 393
  • 495
-1

You can use this:

file = open("text.txt", "r")
lines = file.readlines()
ids = []
lnames = []
fnames = []
jobtitles = []

for line in lines:
    id1, lname, fname, jobtitle = line.split()
    ids.append(id1)
    lnames.append(lname)
    fnames.append(fname)
    jobtitles.append(jobtitle)
Lauro Bravar
  • 363
  • 2
  • 9