Python Forum
Opening file and outputting its text content example
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Opening file and outputting its text content example
#1
If the Python file below is run on a text file containing the following:

Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!


Why does it return empty spaces in the output between each line of text-like below?

Hello! Welcome to demofile.txt

This file is for testing purposes.

Good Luck!



f=open(r"C:\Users\.....\Documents\demofile.txt")
data=None
while data!="":
#If an empty string is returned,
#the file end is reached
    data= f.readline()
    print(data[:])
f.close()
Reply
#2
when you read line from file it also read the new-line char at the end of the line. print() function also add new-line char at the end, so combined you have 2 new-line chars.
one way is to strip the new-line char from line using str.strip() method, the other is to pass end='' to print function.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Thumbs Up Need to compare the Excel file name with a directory text file. veeran1991 1 1,114 Dec-15-2022, 04:32 PM
Last Post: Larz60+
  Modify values in XML file by data from text file (without parsing) Paqqno 2 1,658 Apr-13-2022, 06:02 AM
Last Post: Paqqno
  Extracting Specific Lines from text file based on content. jokerfmj 8 2,955 Mar-28-2022, 03:38 PM
Last Post: snippsat
  Converted Pipe Delimited text file to CSV file atomxkai 4 6,961 Feb-11-2022, 12:38 AM
Last Post: atomxkai
  Facing Problem while opening a file through command prompt vlearner 4 1,904 Jan-30-2022, 08:10 AM
Last Post: snippsat
Thumbs Up Parsing a YAML file without changing the string content..?, Flask - solved. SpongeB0B 2 2,268 Aug-05-2021, 08:02 AM
Last Post: SpongeB0B
  Reading a directory and outputting as sound loungeroom 0 1,220 Jul-30-2021, 09:26 PM
Last Post: loungeroom
  Subprocesses not opening File Select Dialog teut 2 2,404 Feb-22-2021, 08:07 PM
Last Post: teut
  [split] How to convert the CSV text file into a txt file Pinto94 5 3,328 Dec-23-2020, 08:04 AM
Last Post: ndc85430
  Saving text file with a click: valueerror i/o operation on closed file vizier87 5 4,394 Nov-16-2020, 07:56 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

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