1

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) 
1
  • Are you trying to preserve line breaks, or do you want one long string? Commented Dec 22, 2020 at 3:00

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.