Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
次のコードに問題があります。
file = open("file.txt", "r") lines = file.readlines() print lines[0] print lines[1] print lines[2] file.close()
このコードは、行間に改行を与えます。したがって、出力は次のようになります。
line0 line1 line2
これはどのように解決できますか?
readlines()行の配列を返します。すべての行は改行で終わります。
readlines()
ブロック内のすべての行を印刷する場合は、次のようにします。
with open("file.txt", "r") as file: lines = file.readlines() print "".join(lines)
を使用するwithと、これまでに保存できますfile.close()
with
file.close()