Python - 以相反的順序顯示文字檔案的內容?
我們將以相反的順序顯示文字檔案的內容。為此,讓我們首先使用以下內容建立一個文字檔案 amit.txt:
使用切片以相反的順序顯示文字檔案的內容
示例
現在讓我們以相反的順序來讀取以上檔案的內容:
# The file to be read with open("amit.txt", "r") as myfile: my_data = myfile.read() # Reversing the data by passing -1 for [start: end: step] rev_data = my_data[::-1] # Displaying the reversed data print("Reversed data = ",rev_data)
輸出
Reversed data = !tisisihT
透過迴圈以相反的順序顯示文字檔案的內容
示例
# Opening the file to read my_data = open('amit.txt','r') # reversing the data for myLine in my_data: l = len(myLine) rev_data = '' while(l>=1): rev_data = rev_data + myLine[l-1] l=l-1 print("Reversed data = ",rev_data) # Displaying the reversed data
輸出
Reversed data = !tisisihT
廣告