107k views
4 votes
Write a program that will read a file (data.txt). The file contains integer values. The

program will read the file and create a list. (Python)

Write a program that will read a file (data.txt). The file contains integer values-example-1
User Abeba
by
9.3k points

1 Answer

3 votes

Python program that reads in a file called "data.txt" and creates a list of integer values:

# Open the file for reading

with open("data.txt", "r") as file:

# Read the file and split the lines into a list of strings

lines = file.readlines()

# Convert each string in the list to an integer and create a list of integers

integers = [int(line.strip()) for line in lines]

# Print the list of integers

print(integers)

This program uses the built-in open() function to open the file for reading. It then reads in all the lines of the file using readlines() and splits them into a list of strings. It then uses a list comprehension to convert each string in the list to an integer using int() and creates a new list of integers. Finally, it prints the list of integers.

Note that this program assumes that each line in the file contains only a single integer. If your file has a different format (such as multiple integers per line or other types of data), you may need to modify the program accordingly.

User Taylor Leese
by
8.5k points