Printing string item prints individual characters

Printing string item prints individual characters

Help me out. This should be a simple thing but I can't get it to work. I have a text file with five lines. I open and read the lines into an array then print the array successfully but when I print a single item in the array it prints individual characters. I need to use the five input lines as individual strings in the code.


# read the configuration file (from setup.py)

try:
    f = open('interface.txt', encoding="utf-8")
    vars = f.read()
    f.close()
except IOError:
    print("oops cant open interface.txt")
    exit ()

# debug
print ('\nthis works prints five items\n')
print (vars)

print ('\nthis prints every individual character in the file\n')
for xx in vars:
 print (xx)

output:

jbh@junkbox-2:~/Desktop/Athens/Volume1/Chapter00$ ./readInterface.py

this works prints five items

Chapter 00 - Introduction
index.html
../Chapter10/index.html
../Chapter01/index.html
Chapter00.csv


this prints every individual character in the file

C
h
a
p
t
e
r
 
0
0
 
-
 
I
n
t
r
o
d
u
c
t
i
o
n
-- etc. ---

Answer

In your code, vars gets it value here:

    vars = f.read()

That reads the entire content of the file, including line endings, as a single string type value.

You can print that string with:

print(vars)

And that prints the text as you find it in the file, line endings and all.

When you do this instead:

for xx in vars:
    print(xx)

You are looping over the contents of a string, which is just an iterable sequence of characters. So, xx takes the value of those characters one by one, which is why you're seeing them printed one each.

If you want to iterate over the lines, you should either split the string into lines over line endings:

for xx in vars.split('\n'):
    print(xx)

Or, much preferably, read the file as lines to begin with:

try:
    f = open('interface.txt', encoding="utf-8")
    lines = f.readlines()
    f.close()
except IOError:
    print("oops cant open interface.txt")
    exit()

for xx in lines:
    print(xx, end='')  # the lines still include the line endings

It's good that you're being safe with the file and closing it, but even nicer would be:

try:
    with open('interface.txt', encoding="utf-8") as f:
        lines = f.readlines()
except IOError:
    print("oops cant open interface.txt")
    exit(1)

for xx in lines:
    print(xx, end='')

Using with, you are guaranteed that the file will be closed. And by passing 1 to exit() you ensure the program terminates with an exit code of 1, which tells anyone calling the application from elsewhere that things didn't end successfully.

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles