rsajdak
rsajdak

Reputation: 103

Converting a multi-line text file to a python string

I have a text file that has a sequence of four characters a,b,c,d which is 100 lines long that I want to convert to a text string.

There are lines in the txt file that have asterisks that I want to skip entirely.

Here is an example of how the txt file can look. Note the third row has an asterisk where I want to skip the entire row

abcddbabcbbbdccbbdbaaabcbdbab
bacbdbbccdcbdabaabbbdcbababdb
bccddb*bacddcccbabababbdbdbcb

Below is how I'm trying to do this.

s = ''
with open("letters.txt", "r") as letr:
        for line in letr:
            if '*' not in line:
                s.join(line) 

Upvotes: 1

Views: 1416

Answers (2)

dudulu
dudulu

Reputation: 802

Need to use readlines() function.

This is an example, please modify it yourself.

s = ''
with open("letters.txt", "r") as letr:
       result = letr.readlines()

print(result)

for line in result:
    if '*' not in line:
        s += line 
        print(line)

print(s)

I looked at other answers and found that I made a mistake, your code s.join(line) --> s += line is ok.

Upvotes: 2

elonzh
elonzh

Reputation: 1324

s = ''
with open("letters.txt", "r") as letr:
        for line in letr:
            if '*' not in line:
                s += line

builtin type str.method return a string which is the concatenation of the strings in iterable. you should use s += line for contacting string one by one.

Iterate a text file is not a problem.

Upvotes: 1

Related Questions