Reading and taking specific file contents in a list in python

2024/10/13 16:20:03

I have a file containing:

name: Sam
placing: 2
quote: I'll win.name: Jamie
placing: 1
quote: Be the best.

and I want to read the file through python and append specific contents into a list. I want my first list to contain:

rank = [['Sam', 2],['Jamie', 1]]

and second list to contain:

quo = ['I'll win','Be the best']

first off, i start reading the file by:

def read_file():filename = open("player.txt","r")playerFile = filenameplayer = []   #first listquo = []   #second listfor line in playerFile:   #going through each line line = line.strip().split(':')  #strip new line print(line) #checking purposeplayer.append(line[1])     #index out of rangeplayer.append(line[2])quo.append(line[3])

I'm getting an index out of range in the first append. I have split by ':' but I can't seem to access it.

Answer

When you do line = line.strip().split(':') when line = "name: Sam" you will receive ['name', ' Sam'] so first append should work.

The second one player.append(line[2] will not work.

As zython said in the comments , you need to know the format of the file and each blank line or other changes in the file , can make you script to fail.

You should analyze the file differently: If you can rely on the fact that "name" and "quote" are always existing fields in each player data , you should look for this field names.

for example:

for line in file:
# Run on each line and insert to player list only the lines with "name" in itif ("name" in line):# Line with "name" was found - do what you need with itplayer.append(line.split(":")[1])
https://en.xdnf.cn/q/118061.html

Related Q&A

Scipy / ctypes build-config: How to load lib?

These docs have a nice example on how to compile some external C/C++ code and load this using ctypes. This works great with manual compilation (where im controlling the names of my library which later …

Webfaction Django 1.4.1: easy_thumbnails 3.0b – Couldnt get the thumbnail error

I use easy_thumbnails and it works fine on a development machine but in production I get errors like shown below, when I use {% thumbnail photo.image 300x170 %} templatetag. Though can directly browse …

acronym replacement with its value using python

i have dictionary like that i need to replace acronyms in text with its value in dictionary i use this code but it doesnt give me the appropriate result when i test the function using acronyms("we…

Grako - How to do error handling?

How do I do error handling with Grako?EBNF (MyGrammar.ebnf):pattern = { tag | function }* ; tag = tag:( "%" name:id "%" ); function = function:("$" name:id "…

How get the softlayer storage credendials?

Im trying to get the Username,password and host IQN of a authorized Softlayer Network Storage. I used this python script, but the shell returns []import SoftLayerAPI_USERNAME = xxxAPI_KEY = yyyystorage…

dopy.manager.DoError: Unable to authenticate you

Im trying to configure a Virtual Machine(with Vagrant and Ansible), that needs a file.py to the full correct configuration of this machine (according to the book that Im studying),Im was using the Digi…

subprocess.Popen: OSError: [Errno 2] No such file or directory only on Linux

This is not a duplicate of subprocess.Popen: OSError: [Errno 13] Permission denied only on Linux as that problem occurred due to wrong permissions. That has been fixed and this is an entirely different…

Windows Theano Keras - lazylinker_ext\mod.cpp: No such file or directory

I am installing Theano and Keras follwing the How do I install Keras and Theano in Anaconda Python on Windows?, which worked fine for me with an older release before. Now I have upgraded to the latest…

Python Threading: Making the thread function return from an external signal

Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread. test27.pyimport threading import timelock …

Python join data lines together

Hello i have dataset a few thousand lines which is split in even and odd number lines and i cant find a way to join them together again in the same line. Reading the file and overwriting it is fine or …