Python では、ファイルや文字列など、多くのものが反復可能です。ファイルハンドラーを反復処理すると、そのファイル内のすべての行のリストが得られます。文字列を反復すると、その文字列内のすべての文字のリストが得られます。
charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes
for line in open(filePath):
for char in line:
charsFromFile.append(char)
#apply code on each character here
または、ワンライナーが必要な場合
#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]
.
.
編集:agfが使用できる言及としてitertools.chain.from_iterable
つかむ行を指定する機能が必要でない限り、彼の方法の方が優れています
list(itertools.chain.from_iterable(open(filename, 'rU)))
ただし、これには itertools に精通している必要があり、その結果、読みやすさがいくらか失われます
文字を繰り返し処理したいだけで、リストを保存する必要がない場合は、ネストされた for ループを使用します。この方法は、最も読みやすい方法でもあります。