1

Is there an alternative way to split lines from a text file without using the \n in the code? When I use \n to split the text lines, it's a little bit annoying that \n also got printed out in the array lines. here is the code that I use so that the text lines can be split when turning into an array

Combined = open("dictionaries/Combined.txt", 'r', encoding="utf-8")
Example = open("dictionaries/examples.txt", 'w', encoding="utf-8")

for web in Combined:
    Combined_result = re.search(r"([\w-]+\.)*\w+[\w-]*", web)
    Text = (Combined_result.group())
    Example.write((Text+'.web'+'.co.id'+"\n"))

Combined.close()
Example.close()

sample = open("dictionaries/examples.txt", 'r', encoding="utf-8")
websamples = sample.readlines()

websamples

And this is the output that I got, the \n doesn't look good at all when seeing the array output.

['auth.web.co.id\n',
 'access.web.co.id\n',
 'account.web.co.id\n',
 'admin.web.co.id\n',
 'agree.web.co.id\n',
 'blue.web.co.id\n',
 'business.web.co.id\n',
 'cdn.web.co.id\n',
 'choose.web.co.id\n',
 'claim.web.co.id\n',
 'cl.web.co.id\n',
 'click.web.co.id\n',
 'confirm.web.co.id\n',
 'confirmation.web.co.id\n',
 'connect.web.co.id\n',
 'download.web.co.id\n',
 'enroll.web.co.id\n',
 'find.web.co.id\n',
 'group.web.co.id\n',
 'http.web.co.id\n',
 'https.web.co.id\n',
 'https-www.web.co.id\n',
 'install.web.co.id\n']

Thanks!

Tsukuru
  • 65
  • 7
  • Does this answer your question? [How to read a file without newlines?](https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines) – CryptoFool Oct 13 '22 at 06:00

1 Answers1

2

From another question: Getting rid of \n when using .readlines() .

A good approach is instead of using .readlines(), which as you've noticed includes \n characters, and instead using something like.

with open('dictionaries/examples.txt') as f:
    websamples = [line.rstrip() for line in f]

This uses a couple of 'fancier' Python features, that help make it more pythonic.

  • A context manager with the with statement, which automatically closes the file handle at the end of the block, without having to manually call .close().
  • A list comprehension used to create a new array by calling .rstrip() on each line as it is read from the input file.
Damien Ayers
  • 1,551
  • 10
  • 17