简体   繁体   中英

Opening a .txt file in Python and reading every character separately and storing it

I'm new to python and I need this for an exam. I have two txt files that have a movie theater seating data in them. I'm trying to open the file, read the seats that are taken and the ones that are free and want to store this information.

The txt looks a bit like this:

xxxxooxoxxx
xooxoxxoxox
ooxxxoxooxx

os are where the seat is free and xs are taken. so the first seat of the 2nd raw is taken but the 3rd and 4th are free.

I don't know how to properly store data or open a file character by character I guess. I'm really not sure how to start.

I hope, that I understood your question correctly. If your file is not extremely large (more than few 100 MB), then you can propably read whole file and store its content to a variable.

Let say, that this txt file is saved as data.txt . Then you can open a file with this two lines:

with open('data.txt') as f:
    data = f.readlines()

Data is now list of lines.

>>> data
['xxxxooxoxxx\n', 'xooxoxxoxox\n', 'ooxxxoxooxx\n']

Now, I would convert data list to a 2d array of booleans. Here is an ugly one liner:

>>> taken = [[seat == 'x' for seat in row.rstrip()] for row in data]

Now you can determine if seat is taken or not like this:

>>> taken[1][1]
False
>>> taken[1][0]
True

To open a file in the same directory as the python file, use

file=open("file.txt","r")
file1=file.read()

This is how you open a file in read mode (the r ). Now you want to have a list of characters, so you can use the list function.

file1=list(file1)

Now you get a list of all the characters. If you want to split it by newlines, instead of using list, use split.

file1=file1.split('\n')

And finally, close the file.

file.close()

can read a file with open function in python with 'r' option:

with open("file.txt", 'r') as f:
    for row in f:
        for each_char in str(row):
            print each_char
            # Here use your statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM