Python Forum
[Python3] Trailing newline in readlines.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Python3] Trailing newline in readlines.
#5
I observe some things that can be improved (by my subjective opinion).

1. Get random item from list -> use random.choice. Benefits: only one item is needed, returns item (string) right away. Use sample when more than one random item is needed.

>>> pets = ['cat', 'dog', 'rat', 'gerbil', 'hamster', 'guiniepig', 'monkey', 'snake']
>>> random.choice(pets)
'dog'
2. To construct string from different parts -> use f-strings. Benefits: better visual readability, no need for type conversion (if any). Requires 3.6 <= Python.

# Display ai result symbolically.
>>> print(f'{active_pet} ({active_interior}, {active_exterior})\n')
3. Open files -> use with context manager (as in buran examples). Benefits: file will be always properly and automagically closed, no need for close().

with open('data.txt', 'w') as f:
4. Get only first row in file -> use built-in next(). Benefits: whole file content will not be read into memory/list to just get first row. Grab first row from existing fileobject and you are done.

with open('data.txt', 'r') as f:
    my_data = next(f).strip()           # strips newline at the end, can be omitted.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: [Python3] Trailing newline in readlines. - by perfringo - Mar-10-2020, 09:57 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Last record in file doesn't write to newline gonksoup 3 466 Jan-22-2024, 12:56 PM
Last Post: deanhystad
  Facing issue in python regex newline match Shr 6 1,359 Oct-25-2023, 09:42 AM
Last Post: Shr
  Removing leading\trailing spaces azizrasul 8 2,753 Oct-23-2022, 11:06 PM
Last Post: azizrasul
  CSV to Text File and write a line in newline atomxkai 4 2,741 Feb-15-2022, 08:06 PM
Last Post: atomxkai
  [Solved] Using readlines to read data file and sum columns Laplace12 4 3,613 Jun-16-2021, 12:46 PM
Last Post: Laplace12
  openpyxl and newline characters Pedroski55 0 2,986 May-17-2021, 08:56 PM
Last Post: Pedroski55
  Problem with readlines() and comparisons dudewhoneedshelp 2 2,202 Jul-23-2020, 10:21 AM
Last Post: DeaD_EyE
  Reading integers from a file; the problem may be the newline characters JRWoodwardMSW 2 1,987 Jul-14-2020, 02:27 AM
Last Post: bowlofred
  Gnuradio python3 is not compatible python3 xmlrpc library How Can I Fix İt ? muratoznnnn 3 4,957 Nov-07-2019, 05:47 PM
Last Post: DeaD_EyE
  Problem with readlines() assignment Sunioj 5 4,802 Oct-27-2019, 06:20 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020