1. Home
  2. Docs
  3. Python
  4. 檔案
  5. txt檔案讀寫

txt檔案讀寫

寫入全部

f2 = open('test.txt','w')
f2.write('aaaa\nbbbb')
f2.close()

讀取全部

f = open('test.txt')
t1=f.read()
f.close()
print(t1)

讀取一行

with open('session_id.txt', 'r') as f2:
     while True:
         lines = f2.readline()  # 整行讀取資料
         if not lines:
            break

 

讀取一行


from pathlib import Path
fileName='session_id.txt'
my_file = Path(fileName)
if my_file.is_file():
    with open(fileName, 'r') as f2:
        while True:
            lines = f2.readline()  # 整行讀取資料
            print(lines)
            if not lines:
                break