infile = open('my_file.txt', 'r') # Open the file for reading.
data = infile.read() # Read the contents of the file.
infile.close() # Close the file since we're done using it.
# Return a list of the lines, breaking at line boundaries.my_list = data.splitlines()
最终产品:
# Open the file for reading.with open('my_file.txt', 'r') as infile:
data = infile.read() # Read the contents of the file into memory.
# Return a list of the lines, breaking at line boundaries.my_list = data.splitlines()
测试我们的代码:
文本文件的内容:
A fost odatã ca-n povesti,A fost ca niciodatã,Din rude mãri împãrãtesti,O prea frumoasã fatã.
出于测试目的打印语句:
print my_list # Print the list.
# Print each line in the list.for line in my_list:print line
# Print the fourth element in this list.print my_list[3]
输出(由于Unicode字符,外观不同):
['A fost odat\xc3\xa3 ca-n povesti,', 'A fost ca niciodat\xc3\xa3,','Din rude m\xc3\xa3ri \xc3\xaemp\xc3\xa3r\xc3\xa3testi,', 'O preafrumoas\xc3\xa3 fat\xc3\xa3.']
A fost odatã ca-n povesti, A fost ca niciodatã, Din rude mãriîmpãrãtesti, O prea frumoasã fatã.
O prea frumoasã fatã.
from pathlib import Pathfile_path = Path("C:/path/file.txt")lines = file_path.read_text().split_lines()# ... or ...lines = [l.rstrip() for l in file_path.open()]
buffersize = 2**16with open(path) as f:while True:lines_buffer = f.readlines(buffersize)if not lines_buffer:breakfor line in lines_buffer:process(line)
>>> with open("myfile.txt", encoding="utf-8") as file:... x = [l.rstrip("\n") for l in file]>>> x['line 1','line 2','line 3']
使用append:
x = []with open("myfile.txt") as file:for l in file:x.append(l.strip())
或:
>>> x = open("myfile.txt").read().splitlines()>>> x['line 1', 'line 2', 'line 3']
或:
>>> x = open("myfile.txt").readlines()>>> x['linea 1\n', 'line 2\n', 'line 3\n']
或:
def print_output(lines_in_textfile):print("lines_in_textfile =", lines_in_textfile)
y = [x.rstrip() for x in open("001.txt")]print_output(y)
with open('001.txt', 'r', encoding='utf-8') as file:file = file.read().splitlines()print_output(file)
with open('001.txt', 'r', encoding='utf-8') as file:file = [x.rstrip("\n") for x in file]print_output(file)
open('afile') # opens the file named afile in the current working directoryopen('adir/afile') # relative path (relative to the current working directory)open('C:/users/aname/afile') # absolute path (windows)open('/usr/local/afile') # absolute path (linux)
fpath = 'dummy.txt'with open(fpath, "r") as f: lst = [line.rstrip('\n \t') for line in f]
print lst>>>['THIS IS LINE1.', 'THIS IS LINE2.', 'THIS IS LINE3.', 'THIS IS LINE4.']
import csvfpath = 'dummy.txt'with open(fpath) as csv_file:csv_reader = csv.reader(csv_file, delimiter=' ')lst = [row[0] for row in csv_reader]
print lst>>>['THIS IS LINE1.', 'THIS IS LINE2.', 'THIS IS LINE3.', 'THIS IS LINE4.']
import os
# handle files using a callback method, prevents repetitiondef _FileIO__file_handler(file_path, mode, callback = lambda f: None):f = open(file_path, mode)try:return callback(f)except Exception as e:raise IOError("Failed to %s file" % ["write to", "read from"][mode.lower() in "r rb r+".split(" ")])finally:f.close()
class FileIO:# return the contents of a filedef read(file_path, mode = "r"):return __file_handler(file_path, mode, lambda rf: rf.read())
# get the lines of a filedef lines(file_path, mode = "r", filter_fn = lambda line: len(line) > 0):return [line for line in FileIO.read(file_path, mode).strip().split("\n") if filter_fn(line)]
# create or update a file (NOTE: can also be used to replace a file's original content)def write(file_path, new_content, mode = "w"):return __file_handler(file_path, mode, lambda wf: wf.write(new_content))
# delete a file (if it exists)def delete(file_path):return os.remove() if os.path.isfile(file_path) else None
然后您将使用FileIO.lines函数,如下所示:
file_ext_lines = FileIO.lines("./path/to/file.ext"):for i, line in enumerate(file_ext_lines):print("Line {}: {}".format(i + 1, line))