Как прочитать текстовый файл в список в Python (с примерами)
Вы можете использовать один из следующих двух методов для чтения текстового файла в список в Python:
Способ 1: Используйте open()
#define text file to open my_file = open('my_data.txt', 'r') #read text file into list data = my_file.read()
Способ 2: использовать loadtxt()
from numpy import loadtxt #read text file into NumPy array data = loadtxt('my_data.txt')
В следующих примерах показано, как использовать каждый метод на практике.
Пример 1: Чтение текстового файла в список с помощью open()
В следующем коде показано, как использовать функцию open() для чтения текстового файла с именем my_data.txt в список в Python:
#define text file to open my_file = open('my_data.txt', 'r') #read text file into list data = my_file.read() #display content of text file print(data) 4 6 6 8 9 12 16 17 19
Пример 2: Чтение текстового файла в список с помощью loadtxt()
В следующем коде показано, как использовать функцию NumPy loadtxt() для чтения текстового файла с именем my_data.txt в массив NumPy:
from numpy import loadtxt #import text file into NumPy array data = loadtxt('my_data.txt') #display content of text file print(data) [ 4. 6. 6. 8. 9. 12. 16. 17. 19.] #display data type of NumPy array print(data. dtype ) float64
Хорошая вещь в использовании loadtxt() заключается в том, что мы можем указать тип данных при импорте текстового файла с помощью аргумента dtype .
Например, мы можем указать текстовый файл для импорта в массив NumPy как целое число:
from numpy import loadtxt #import text file into NumPy array as integer data = loadtxt('my_data.txt', dtype='int') #display content of text file print(data) [ 4 6 6 8 9 12 16 17 19] #display data type of NumPy array print(data. dtype ) int64
Примечание.Полную документацию по функции loadtxt() можно найти здесь .
Дополнительные ресурсы
Следующие руководства объясняют, как читать другие файлы в Python:
Import Text File in Python
- Use the open() Function to Import a File in Python
- Use the numpy.genfromtxt() Function to Import a File in Python
Like in the other popular programming languages like C, C++, etc., Python supports file handling. It allows the programmers to deal with files and essentially perform some basic operations like reading, writing, and some other file handling options to operate on files.
There is no requirement for importing external libraries to read and write files in Python. Python provides built-in functions for reading, writing, and creating files.
The text or binary files can be opened for reading, writing, and modifying, but they cannot be imported. The word import might be a little misleading here, so we will refer to it as opening a file in the whole article.
Use the open() Function to Import a File in Python
The open() function, as its name suggests, is used to open a text or binary file in Python. It is a built-in function, and therefore, it can be used without importing any module.
The syntax of the open() function is below.
open(path_to_file, mode)
The open() function has a couple of parameters, but the most important ones are the first two, namely path_to_file and mode .
The path_to_file mode specifies the path or name of the file, while the mode parameter specifies the mode in which we want to open the file.
The following code uses the open() function to open a text file in Python.
f = open("file1.txt", "r")
This line of code opens the file named file.txt in reading mode.
The opened file will remain open until it is manually closed by the programmer using the close() function. Closing the file that is no longer in use is essential as if it is not closed, the file might get corrupted, or the whole program might crash.
The following code uses the close() function to close the file in Python.
f.close()
Use the numpy.genfromtxt() Function to Import a File in Python
The NumPy library needs to be imported to use the genfromtxt() function.
NumPy , an abbreviation for Numerical Python, is a library used in Python that consists of multidimensional array objects and an assembly of methods for processing these arrays. Logical and mathematical operations can be performed on arrays using NumPy .
The genfromtxt() function is used to load data from a text file. It is especially helpful in dealing with numbers and comes in handy when some missing values need to handled as specified.
The following code uses the genfromtxt() function to open a text file in Python.
import numpy as np . f = np.genfromtxt(fname="file1.txt")
import gives access to other modules in the Python program. On the other hand, the files are either text or Binary, and they are not modules. Modules can be imported into the Python code, but the files can only be opened using the two commands mentioned in this article.
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
Related Article — Python File
- Get All the Files of a Directory
- Append Text to a File in Python
- Check if a File Exists in Python
- Find Files With a Certain Extension Only in Python
- Read Specific Lines From a File in Python
- Check if File Is Empty in Python
можно ли импортировать .txt или .ini файл как .py файл?
Есть список констрант и настроек, которые хотелось бы добавлять в py файл через import, но каждый раз открывать с блокнота не оч удобно.
Есть ли возможность импортировать .txt или .ini файл как .py файл? Как себя поведет программа при сборке через nuitka или Pyinstaller? Вот пример переименования:
import os os.rename('tt.txt', 'tt.py') from tt import * print(x) os.rename('tt.py', 'tt.txt')
Отслеживать
задан 18 июн 2021 в 8:26
399 4 4 серебряных знака 15 15 бронзовых знаков
к примеру: можно наверное переименовывать файл настроек из ini в py перед импортом.
18 июн 2021 в 8:59
Если очень хочется, то можно загрузить файл в память и выполнить через exec. Но лучше не использовать исполняемый формат для хранения настроек.
18 июн 2021 в 9:50
Накидайте пример, не оч понимаю
Как импортировать txt в python

import pandas as pd df = pd.read_csv('prices.txt', sep ='\t', header = None) df.columns = ['Товар', 'Количество', 'Цена'] df['Итого'] = df['Количество'] * df['Цена'] summa_zakaza = sum(df['Итого']) print(summa_zakaza)
with open('prices.txt') as f: print(sum(eval('*'.join(s.split()[1:])) for s in f))
with open('prices.txt') as f: print(sum(map(lambda x: int(x[1]) * int(x[2]), map(str.split, f.readlines()))))
from functools import reduce with open('prices.txt') as f: file = open('prices.txt', mode='r', encoding='utf-8') print(reduce(lambda x, y: x + int(y[1]) * int(y[2]), [i.split('\t') for i in [i.strip() for i in file.readlines()]], 0))
Больше полезных материалов вы найдете на нашем телеграм-канале «Библиотека питониста»
Поиск слова в текстовом файле
Напишите программу, которая принимает поисковый запрос и выводит названия текстовых файлов, содержащих искомую подстроку. Все файлы располагаются в директории D:\Python\Textfiles.
Формат ввода
Строка, содержащая поисковый запрос.
Формат вывода
Список текстовых файлов, содержащих введенную пользователем подстроку.
Пример ввода:
словарь
Пример вывода:
challenges-for-beginners-5.md dictionaries-2.md dictionaries.md challenges-for-beginners.md merge-dictionaries.md dictionaries-4.md dictionaries-3.md
Решение
Поскольку слово может встречаться в одном и том же файле несколько раз, есть смысл сохранять результаты поиска во множестве set .
import os if __name__ == '__main__': folder = 'D:\\Python\\Textfiles' answ = set() search = input() for filename in os.listdir(folder): filepath = os.path.join(folder, filename) with open(filepath, 'r', encoding = 'utf-8') as fp: for line in fp: if search in line: answ.add(filename) for i in answ: print(i)
Словарь из CSV-файла
Имеется файл data.csv, содержащий информацию в csv-формате. Напишите функцию read_csv() для чтения данных из этого файла. Она должна возвращать список словарей, интерпретируя первую строку как имена ключей, а каждую последующую строку как значения этих ключей. Функция read_csv() не должна принимать аргументов.
Решение
import csv def read_csv(): with open("data.csv") as f: a = [ for row in csv.DictReader(f, skipinitialspace=True)] return a
def read_csv(): with open('data.csv') as file: keys = file.readline().strip().split(',') return [dict(zip(keys, line.strip().split(','))) for line in file]
def read_csv(): with open('data.csv', encoding='utf-8') as file: info = list(map(lambda x: x.strip().split(','), file.readlines())) return [dict(zip(info[0], j)) for j in info[1:]]
from csv import DictReader def read_csv(): with open('data.csv') as file_object: data = DictReader(file_object) ans = list(data) return ans
def read_csv(): with open("data.csv") as data_file: dict_list = [] keys = data_file.readline().strip().split(",") for values in data_file: dict_list.append(dict(zip(keys, values.strip().split(",")))) return dict_list
Информация о файле
Имеется файл file.txt с текстом на латинице. Напишите программу, которая выводит следующую статистику по тексту:
- количество букв латинского алфавита;
- число слов;
- число строк.
Пример ввода и вывода
Предположим, что file.txt содержит приведенный ниже текст:
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated.
В этом случае программа должна вывести информацию о файле в следующем виде:
Input file contains: 108 letters 20 words 4 lines
Решение
with open('file.txt') as f: txt = f.read() print('Input file contains:') print(sum(map(str.isalpha, txt)), 'letters') print(len(txt.split()), 'words') print(txt.count('\n') + 1, 'lines')
with open('file.txt') as f: res = f.readlines() f.seek(0) words = f.read().split() let = sum(len([y for y in x if y.isalpha()]) for x in words) print('Input file contains:') print(f' letters') print(f' words') print(f' lines')
with open('file.txt') as f: print('Input file contains:') print(len(list(filter(lambda x: x.isalpha(), f.read()))), 'letters') f.seek(0) print(len(f.read().split()), 'words') f.seek(0) print(len(list(f.readlines())), 'lines')
with open('file.txt') as file: lst = file.read() lines = lst.count('\n') + 1 words = len(lst.split()) letters = len([c for c in lst if c.isalpha()]) print(f'Input file contains:\n letters\n words\n lines')
with open('file.txt') as f: t = f.read() f.seek(0) print('Input file contains:') print(f' letters') print(f' words') print(f' lines')
Запрещенные слова
Напишите программу, которая получает на вход строку с названием текстового файла, и выводит на экран содержимое этого файла, заменяя все запрещенные слова звездочками * (количество звездочек равно количеству букв в слове). Запрещенные слова, разделенные символом пробела, хранятся в текстовом файле forbidden_words.txt. Все слова в этом файле записаны в нижнем регистре. Программа должна заменить запрещенные слова, где бы они ни встречались, даже в середине другого слова. Замена производится независимо от регистра: если файл forbidden_words.txt содержит запрещенное слово exam, то слова exam, Exam, ExaM, EXAM и exAm должны быть заменены на **** .
Формат ввода
Строка текста с именем существующего текстового файла, в котором необходимо заменить запрещенные слова звездочками.
Формат вывода
Текст, отредактированный в соответствии с условием задачи.
Пример ввода вывода
Предположим, что forbidden_words.txt содержит следующие запрещенные слова:
hello email python the exam wor is
А текст файла, подлежащего цензуре, выглядит так:
Hello, world! Python IS the programming language of thE future. My EMAIL is. PYTHON is awesome.
Тогда программа должна вывести отредактированный текст в таком виде:
*****, ***ld! ****** ** *** programming language of *** future. My ***** **. ****** ** awesome.
Решение
with open('forbidden_words.txt') as forbidden_words, open(input()) as to_change: pattern, text = forbidden_words.read().split(), to_change.read() text_lower = text.lower() for word in pattern: text_lower = text_lower.replace(word, '*' * len(word)) result = ''.join((y, x)[x == '*'] for x, y in zip(text_lower, text)) print(result)
with open('forbidden_words.txt') as f: forbidden_words = with open(input()) as f: s = f.read() s_lower = s.lower() for forbidden_word in forbidden_words: s_lower = s_lower.replace(forbidden_word, forbidden_words[forbidden_word]) print(*map((lambda c1, c2: '*' if c2 == '*' else c1), s, s_lower), sep='')
with open("forbidden_words.txt", encoding="utf-8") as file, open(input()) as infile: text = infile.read() for f in file.read().strip("\n").split(): pos = text.lower().find(f) while pos > -1: text = text[:pos] + "*" * len(f) + text[pos+len(f):] pos = text.lower().find(f) print(text)
import re with open(input()) as inp, open('forbidden_words.txt') as fw: text, forbidden = inp.read(), fw.read().split() for i in forbidden: text = re.sub(i, '*' * len(i), text, flags=re.I) print(text)
with open(input(), encoding='utf-8') as r, open('forbidden_words.txt', encoding='utf-8') as s: w = s.read().split() v = r.read() l = v.lower() for i in w: l = l.replace(i, '*' * len(i)) [print(j if j == '*' else i, end='') for i, j in zip(v, l)]
Материалы по теме
- Задача о поврежденной XML-строке
- 5 задач с решениями на Python для начинающих разработчиков
- 5 классических задач по Python для начинающих с решениями
