Reputation: 27
I tried to print the length of the .txt files. There was no problem when I tested with the first function. But when I tried to make .txt file to string at the second function, the txt file was empty. (sorry for my horrible explanation)
here's my code
#civilization
#variable
total = 0
#opening files
fire = open("fire.txt")
wheel = open("wheel.txt")
lever = open("lever.txt")
agriculture = open("agriculture.txt")
earthware = open("earthware.txt")
#functions
def read_files(document):
document_str = document.read()
return document_str
def get_total_characters(doc):
text = read_files(doc)
blank = 0
for x in text:
if x == " ":
blank += 1
text_length = len(text) - blank
print(text_length)
def get_total_words(doc):
t = read_files(doc)
word_list = t.split()
print(word_list)
#def get_avarage_charaters_in_words():
get_total_characters(fire)
get_total_words(fire)
and this is what happens
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
================= RESTART: D:\카이스트 수업 관련\과제 3\code_3\3_code.py =================
1770
[]
>>>
I dont't know why the list is empty
thank you
Upvotes: 0
Views: 72
Reputation: 7006
When you open a file in python and read it, you have reached the end of the file, so if you try to read it again, there is nothing left to read.
In order to "Start the book again" you need to tell python to start at the beginning of the file.
You could do the following between the two function calls
fire.seek(0)
which tell python to go back to the start of the file called fire
Upvotes: 1