Skip to main content

[Python] Notebook-4 Introduction to Python: Fundamentals—Part.2


下半部分關於開啟文件和讀寫的筆記上線囉!

來自同一門課—Introduction to Python: Fundamentals
只是因為怕內容太多,
所以才分成兩回。

內容有reading and writing of text files、.tell()、.read()、.readline()、.readlines()、.seek()、.strip()
and .close() functions。


# -*- coding: utf-8 -*-
"""
Created on Wed Sep  13 21:44:17 2017
@author: ShihHsing Chen
This is a note for the class 
"Introduction to Python: Fundamentals".
"""

#Finally, we can import text files and read it! Thank God. Orz
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" r  = READ-ONLY, reports errors if the file does not exist            "
" r+ = READ-AND-WRITE, reports errors if the file does not exist       "
" w  = WRITE-ONLY, overwrites the file with the same name if it exists "
" w+ = READ-AND-WRITE, creates a new file if it does not exist         "
" a  = WRITE-ONLY, append text at the end of file                      " 
" a+ = READ-AND-WRITE, append text at the end of file (no overwrites)  "
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
#You can use the following statement or that one outside the comment area to 
#open a text file. Remember, what you do is just "open." You still need 
#other statements to read and write.
#news_file = open("news.txt", "r") 
news_file = open("D:/Introduction to Python/news.txt", "r")

#After opening a file, we can use .read(digit) to specify how many characters 
#we want to read with the variable "digit."
#We also have .readlines() to turn each line into different strings in a list
#and .readline() to read in one line of string at a time.
#By the way, .tell() gives you the current position of the pointer.
print(news_file.tell())
news_content_1 = news_file.read(10)
print(news_content_1)
print(news_file.tell(), "\n")

news_content_2 = news_file.readlines()
print(news_content_2, "\n")

#Once you .read() the file, the pointer goes to the end of file. 
#To reset the pointer, you can use .seek(0) 
#Second way to do so is close the file and reopen it.
#Third way to do so is working with the file_object alternatively. 
#For our example below, the file object is news_content_4, a string. 
#With our previous experience, we can iterate through the string with 
#different indexes.
print(news_file.tell())
news_file.seek(0)
print(news_file.tell(), "\n")

#Citations from "Learning Python, forth edition" by Mark Lutz.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
The first of these, the while statement, provides a way to code general loops. 
The second, the for statement, is designed for stepping through the items in 
a sequence object and running a block of code for each.

It is called a “loop” because control keeps looping back to the start of the 
statement until the test becomes false. When the test becomes false, control 
passes to the statement that follows the while block.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

#Here are three one-word statements for while loops and for loops.
#Also from "Learning Python, forth edition" by Mark Lutz.
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" break:    Jumps out of the closest enclosing loop                    "
"           (past the entire loop statement)                           "
"                                                                      "
" continue: Jumps to the top of the closest enclosing loop             "
"           (to the loop’s header line)                                "
"                                                                      "
" pass:     Does nothing at all: it’s an empty statement placeholder   "
"           (A placeholder make it easier to add more content.)        "
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

#If we combine a while loop with .readline(), they will print out each line 
#with an extra \n at the end of line. To remove it or other carachters, 
#we can use .strip()
news_content_3 = news_file.readline().strip()
count1 = 0

while news_content_3:
    print(count1, news_content_3)
    news_content_3 = news_file.readline().strip()
    count1 += 1
else:
    print() #If you put pass here, it is a placeholder.

#Or else, we can use for/in plus if to form a loop to replace the while loop, 
#but we have to count the number of lines first and while iterating, which is 
#not required for while loop. As a result, while loops do have their reasons 
#to exist. 
news_file.seek(0)
lines = len(news_file.readlines())
news_file.seek(0)

news_content_4 = news_file.readline().strip()
count2 = 0

for count2 in range(0, lines):
    print(count2, news_content_4)
    news_content_4 = news_file.readline().strip()
    count2 = count2 + 1
else:
    print() #If you put pass here, it is a placeholder.

#Caution: When you finish your work, remember to close the file with .close()
#and release the memory.
news_file.close()

#After reading, here comes the thing that many students hate. It is "WRITING."
#To do so, we use the .write()
test_file = open("D:/Introduction to Python/writing.txt", "w")
test_file.write("Hero comes and goes, but legend is forever.")
test_file.close()

test_file = open("writing.txt", "r")
test_content = test_file.read().title()
print(test_content)
test_file.close()

# Code example in the last module of "Introduction to Python: Fundamentals"
#It helps us review many things we talked before so I insert it here.
def logger(log):
    log_entry = input("enter log item (enter to quit): ")
    count = 0

    while log_entry:
        count += 1
        log.write(str(count) + ": " + log_entry + "\n")
        log_entry = input("enter log item (enter to quit): ")
        
    return count
    
log_file = open('log_file.txt', 'w+')
log_file.close()

log_file = open('log_file.txt', 'a+')
logger(log_file)    

log_file.seek(0)
log_text = log_file.read()

print()
print(log_text)
log_file.close()

Comments

Popular posts from this blog

[申辦綠卡] EB-2 NIW 國家利益豁免綠卡申請教學(一)找合作的律師事務所

Image by  David Peterson  from  Pixabay

[申辦綠卡] EB-2 NIW 國家利益豁免綠卡申請教學(零)名詞解釋 Petitioner vs Applicant

Image by  David Peterson  from  Pixabay

[申辦綠卡] EB-2 NIW 國家利益豁免綠卡申請教學(七)組裝 NIW I-140 申請文件包

Image by  David Peterson  from  Pixabay