Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Sunil Padmanabhan
1,344 PointsAvoid Additional Line Spaces when reading from Text Files
I have written below code to Write and Read from a text file. When reading from the text file, I want to avoid the additional line spaces. How can that be done? ..........................................
import datetime
def buildGroceryList(grocery,count): #file = open("GroceryList.txt", 'a')
with open("GroceryList.txt", 'a') as file: #Defining it this way does not require us to explicity close the file
current_date=datetime.datetime.today()
if count==1:
current_date = datetime.datetime.today()
file.write('\n')
file.write(datetime.datetime.strftime(current_date, '%d-%b-%Y'))
file.write('\n')
file.write(str(sno)+'.'+grocery)
#file.close()
def showGroceryList():
with open("GroceryList.txt") as file: # Defining it this way does not require us to explicity close the file
for line in file:
print(line)
print("Build you Grocery List") print("-"*30) quit=''
sno=0 while quit=='': sno=sno+1 buildGroceryList(input("Enter a Grocery Item\n"),sno) print('-'*30) quit=input('Press Enter to Add another Item or Press any other key to Quit')
print("Your Grocery List") showGroceryList()
1 Answer
Dave StSomeWhere
19,870 PointsCould you please provide what the text file looks like and explain what you mean by extra line spaces. Are you talking about blank lines in the file, white space at the beginning or end of a line or ???
Also, sounds like you are happy with how the file is written and are just having an issue with reading the file right?