-1

Basically I have this code that copies lines that contain a specific word and writes them in another file.

with open("test.txt", encoding='latin1') as f:
with open("output.txt", "a") as f1:
    for line in f:
        if str("Hello") in line:
            f1.write(str(line.encode('UTF-8')) + "\n")

So what I'm trying to do is copy lines from test.txt that contain "Hello" and paste them in output.txt. For example the output should look like this:

Hello There

He said Hello

But I have this error where each line will look like this: b'Hello There\n'

The reason I have + "\n" in the code, is because without it, the file will write them all in a single line.

Anyone know how to fix it? :(

Kirby
  • 1
  • 1

2 Answers2

0

You do not need to convert string to bytes and back, you can use

with open("test.txt", encoding='latin1') as f:
    with open("output.txt", "a") as f1:
        for line in f:
            if "Hello" in line:
                f1.write(line)

Note you do not need to add \n here, as the newlines are kept when reading the lines with for line in f.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • I tried this code and it does work but when I try it on some files (large files with a lot of symbols as text), some lines have a lot of symbols and when it gets there: it crashes, saves what it got and stops there (doesn't skip and continue) Here's the crash log: https://imgur.com/a/V4qsetp Is there a way to fix this? I've been trying to look it up for a while, or is there like a way to make it skip lines that it can't read or something? Thank you btw – Kirby Jun 21 '21 at 00:05
  • @Kirby This is a [very common issue](https://stackoverflow.com/questions/27092833/unicodeencodeerror-charmap-codec-cant-encode-characters), and I cannot help much without the exact file you have. If you can share a small version of the file, I could help more. – Wiktor Stribiżew Jun 21 '21 at 08:18
0

When you call encode() you are effectively turning the string into a byte object. You can either specify the encoding in the with statement of the file you wish to write to, or you can call decode() after encode().

Ralvi Isufaj
  • 442
  • 2
  • 9