Read () another text file output

Results of this code:

!/usr/bin/python
from sys import argv
script, file = argv
apertura = open(file,'r')

for a in apertura:
    print(apertura.read())

is an:

quarta quinta
sesta
settima
ottava
nona

I want to print the whole file using read (). The above code skips some lines. What for?

The contents of the file are as follows:

prima seconda terza
quarta
quinta
sesta
settima
ottava
nona
+4
source share
5 answers

The problem is that you are mixing two methods of reading a file.

for a in apertura:          # this reads in the first line of the file
    print(apertura.read())  # this reads the remainder of the file in one chunk

So, the first line of the file is never printed.

You can iterate through a line of a line as follows:

for a in apertura:
    print(a)

You can also use the context manager to make sure the file is closed later

#!/usr/bin/python
from sys import argv
script, file = argv
with open(file, 'r') as apertura:
    for a in apertura:
        print(a)

If you really want to read the file with .read(), the code is a bit simpler, but uses a lot of memory in case the file is large

#!/usr/bin/python
from sys import argv
script, file = argv
with open(file, 'r') as apertura:
    print(apertura.read())
+6
source

To print the entire file:

!/usr/bin/python
from sys import argv
script, file = argv
apertura = open(file,'r')
print apertura.read()

:

!/usr/bin/python
import sys
print open(sys.argv[1]).read()
+1
for word in apertura.read().split():
    print (word)
0

:

for line in apertura.readlines():
    print line

.

-1

with open ('C: \ Users \ 33382 \ Desktop \ pf.txt', 'r') as f: lines = f.readlines ()

for lines in lines: print a line

-1
source

Source: https://habr.com/ru/post/1622065/


All Articles