Search code examples
pythontext-filesfile-handlingdata-extraction

How to read a text(.txt) file in python line by line with delimiters without pandas?


I have a text file with about 2113 lines in which data is is stored in the format string:integer and I need to store both the string and the integers as an array in variables status and next_move. I have done it with pandas but I want to find a way to do it without using pandas.

The data file is as follows:

.....
OOXXX O X:5
OOXXX OX :5
OOXXXO  X:6
OOXXXO X :6
OOXXXOOXX:None
OOXXO  XX:5
OOXXO X X:7
OOXXO XX :8
OOXXOX X :8
OOXXOXX  :7
....

The code I used with pandas is this :

  df = pd.read_csv("Dataset.txt", sep=":", names=['strings', 'moves'])
    a = df[['strings']]
    b = df[['moves']]
    status = a.to_numpy()
    next_move = b.to_numpy()
    status = status.flatten()
    next_move = next_move.flatten()

Solution

  • You can use csv library.

    status = []
    next_move = []
    with open("Dataset.txt") as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=":")
        for row in csv_reader:
            status.append(row[0])
            next_move.append(row[1])