Appending the elements of a list after importing them from a file in Python

My goal is to read elements from a file, add each line to print its output. However, I have been unsuccessful in my attempts so far. For example, if I try to access a certain number:

with open('test.txt', 'r') as f:
    for line in f:
         for s in line.split(' '):
             num = int(s)
             print(num[1])

TypeError: 'int' object is not subscriptable

I also tried another approach by reading each line, storing it in a list, and then converting it into an integer to use them later:

with open('test.txt', 'r') as f:
    filer = f.readlines()
    filer = map(int, filer)
    print(filer[1])

Unfortunately, this method also resulted in an error:

TypeError: 'map' object is not subscriptable

As a beginner in Python, I am still learning and trying to figure out the best way to achieve my goals.

Answer №1

When using Python 3.x, the map function will return a map object that does not support indexing.

If you need to access elements in the map object, you can convert it to a list using the built-in function list:

with open('test.txt', 'r') as f:
    filer = f.readlines()
    filer = list(map(int, filer))
    print(filer[1])

Another option is to use a list comprehension for a more concise approach:

with open('test.txt', 'r') as f:
    filer = f.readlines()
    filer = [int(x) for x in filer]
    print(filer[1])

Additionally, it's worth mentioning that the open function in Python defaults to read-mode, so you can omit the mode argument:

with open('test.txt') as f:

Nevertheless, some developers prefer to include the explicit 'r' for clarity, so the choice is yours to make.

Answer №2

It appears that you are saving your data as a single number, but it would be better to use a list for better organization. Give this code a try:

with open('data.txt', 'r') as file:
    dataList = []
    for item in file:
         for element in item.split(' '):
             dataList.append(int(element))       
             print(dataList[-1])

Answer №3

If you only need to access one number at a time, consider modifying the code from print(num[1]) to simply print(num).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for narrowing down a sqlalchemy query based on a specific field within the most recent child entry

My current database structure consists of two tables that are roughly described in SQLAlchemy mapping as follows: class Parent(Base): __tablename__ = "parent" parent_id = Column(Integer, primary_key=True) class Child(Base): __tablename__ = " ...

"Decoding Hydra: What's the Best Way to Represent 'None' in Configuration Files

I am facing an issue with a Python script that I have created. Here is the script: import hydra from omegaconf import DictConfig, OmegaConf @hydra.main(version_base="1.3", config_path=".", config_name="config") def main(cfg: ...

What is the process for loading a webpage into another webpage with google app engine?

Hey there, I'm a newbie to app engine and could really use some help, I'm looking to replicate the functionality of the jquery load function on the server side within a RequestHandler's get() method. Currently, I have a page that looks some ...

Challenge with Jinja2 formatting

How can I declare a fact in ansible using Jinja2? I encountered the following error: Error: template error while templating string: expected token ',', got ':' Here is the code snippet: - set_fact: lb_lstnr_map: [] - name: "Bui ...

How can one best tackle the solution of a differential equation at each interval of time?

Is there a suitable equation solver for a timestep scenario? I have tried using ODEint, Solve_ivp, and even sympy to solve a first order differential equation like this: dTsdt = Ts* A - B + C # Defined in a function. This is the mathematical model. wh ...

Looking to access nasdaq.com using both Python and Node.js

Having an issue with a get request for nasdaq.com. Attempting to scrape data with nodejs, but only receiving 'ECONNRESET' after trying multiple configurations. Python, on the other hand, works flawlessly. Currently using a workaround by fetching ...

Merge together all the columns within a dataframe

Currently working on Python coding in Databricks using Spark 2.4.5. Trying to create a UDF that takes two parameters - a Dataframe and an SKid, where I need to hash all columns in that Dataframe based on the SKid. Although I have written some code for th ...

Eliminate redundant rows by comparing assorted columns and conditions within Python

In my dataset, I have the following columns. CUI1 CUI2 RELA SL CUI_x SAB_x CODE_x STR_x TTY_x CUI_y SAB_y CODE_y STR_y TTY_y C0010356 C0205721 same_as SNOMEDCT_US C ...

Using the key from a nested CSV file as the primary key in Python

Sorry for the confusing title. I have a csv file with rows structured like this: 1234567, Install X Software on Y Machine, ServiceTicket,"{'id': 47, 'name': 'SERVICE BOARD', '_info': {'board_href': ' ...

The problem with importing a pre-defined Selenium function in the browser

Initial Set-up Working with selenium, I found myself constantly redefining functions. To streamline the process, I decided to create a separate file for these functions and import them as needed in my work files. A Basic Example Initially, when all fun ...

What is the best way to exchange configuration data among Javascript, Python, and CSS within my Django application?

How can I efficiently configure Javascript, Django templates, Python code, and CSS that all rely on the same data? For example, let's say I have a browser-side entry widget written in Javascript that interacts with an embedded Java app. Once the user ...

How can you pull information from Finnhub.io? (incorporating JSON into a pandas data table)

As a novice in coding, I am eager to learn and explore data from stock markets. My attempt at importing data from finnhub has not been successful so far. import requests import json r = requests.get('https://finnhub.io/api/v1/stock/candle?symbol=QQQ& ...

Running Anaconda on an Ubuntu system with 32-bit architecture

I'm interested in utilizing the mlbox package (view here) that is specifically designed to work with a 64-bit version of Python. However, my current system runs on a 32-bit version of Ubuntu. Is it possible for me to install a 64-bit python without en ...

Detect Peaks in a Graph Using Python

Upon generating a plot, I noticed that it displays numerous waves. My goal now is to determine the total number of full waves present in this chart. Based on my annotations, there should be a total of 7 full waves visible. I attempted to smoothen out the c ...

Visualizing data with Matplotlib: Histogram displaying frequency in thousands

I am currently working on a histogram in matplotlib that contains around 260,000 data points. The issue I am facing is that the y-axis on the histogram displays high numbers like 100,000. What I would prefer is to have the y labels represent thousands ins ...

Is it possible to utilize a yyyy-mm-w format when plotting datetime data?

I am currently working with a dataset that is recorded on a weekly basis and I want to create a matplotlib plot using this information. The date format I am using is yyyymmw, where w represents the week of the month (ranging from 1 to 5). Each week starts ...

Transforming data in Pandas by consolidating multiple columns into a single column

I have some data that needs to be reshaped to better organize the results. The data consists of initial columns followed by a varying number of columns grouping the data. Each group is marked with an 'x' if the key belongs to it, with keys potent ...

Adding a basic function within a Django HTML template can enhance the functionality and flexibility

Currently, I have a function named "copyright" in my project that generates a dynamic copyright message. My goal is to incorporate this function into my base Django template as shown below: def copyright(): // code here // more code here print(fi ...

I encountered a PermissionError while trying to log in as an administrator

Just starting out with django and I'm trying to create a superuser. After following all the necessary steps, the terminal confirms that I have successfully created the superuser. However, when I go to the server, I encounter a permission error. I eve ...

I am encountering a 404 error when attempting to make a GET request for a file located in the same directory

Here is the Javascript code that utilizes the get method. The directory contains both files - the HTML file where the JS code resides, and the text file. Below is an image of the console displaying errors. ...