Skip to content

Instantly share code, notes, and snippets.

@mayankdawar
Created March 16, 2020 10:34
Show Gist options
  • Save mayankdawar/23e65460e1e0797a0a021d076bc88217 to your computer and use it in GitHub Desktop.
Save mayankdawar/23e65460e1e0797a0a021d076bc88217 to your computer and use it in GitHub Desktop.
Write code to find out how many lines are in the file emotion_words.txt as shown above. Save this value to the variable num_lines. Do not use the len method.
#Write code to find out how many lines are in the file emotion_words.txt as shown above. Save this value to the variable num_lines. Do not use the len method.
file = open("emotion_word.txt","r")
count = 0
for aline in file.readlines():
count += 1
num_lines = count
@hadrocodium
Copy link

"""
Write code to find out how many lines are in the file emotion_words.txt as shown above. Save this value to the variable num_lines. Do not use the len method.

"""

I like generator comprehensions because they yield each item out of the expression, one by one. And because of it, it saves a lot of memory.
https://stackoverflow.com/questions/364802/how-exactly-does-a-generator-comprehension-work

with open('emotion_words.txt', 'r') as fileref:
    num_lines = sum(1 for line in fileref)
    print(num_lines)

@ghost311
Copy link

ghost311 commented Jan 1, 2023

thank you!

@misspage
Copy link

#To create a string called first_forty comprised of the first 40 characters of the file "emotion_words2.txt,"

python
Copy code

Open the file in read mode and read the first 40 characters

with open("emotion_words2.txt", "r") as file:
first_forty = file.read(40)

Print the first 40 characters (optional)

print("First 40 characters:", first_forty)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment