檔案的寫入

2021-09-22 05:40:02 字數 1071 閱讀 2090

# os.path.exists 判斷某個檔案是否存在,如果存在返回true 不存在返回false

# is_exist = os.path.exists('1.txt')

# if is_exist == true:

# file_handle = open('1.txt','r')

file_handle = open('1.txt', 'w')

# write()

file_handle.write('hello world\n')

file_handle.write('你好\n')

# writelines() 將乙個存放字串的列表整個寫入檔案,不會自動新增換行符

name_list = ['張三\n','李四\n','王五\n']

file_handle.writelines(name_list)

# 3.關閉檔案

file_handle.close()

if os.path.exists('1.txt'):

# 1.開啟檔案

file_handle = open('1.txt','r')

# 2.讀取檔案

# 2.1.read() 會將檔案中的所有資料都讀取出來

# content = file_handle.read()

# 2.2readline() 會讀取一行資料,會把游標移動到該行末尾,下次再執行readline將會讀取下一行

# content = file_handle.readline()

# print content

# content = file_handle.readline()

# print content

# 2.3.readlines() 會讀取檔案中的所有行,把每一行的資料放在列表中返回

con_list = file_handle.readlines()

print con_list

# 3.關閉檔案

file_handle.close()

日誌寫入到檔案 多檔案寫入

在上篇文章的基礎上,修改配置 log4j.rootlogger info,fout 說明 rootlogger是可以多樣式定義的,如log4j.rootlogger info,myout,fout。myout,fout是自定義樣式。這樣就會在c盤下建立a.log檔案。有這樣一種需求,不同模組需要各自...

python檔案的寫入

wirte 方法把字串寫入檔案,writelines 方法可以把列表中儲存的內容寫入檔案。f file hello.txt w li hello world n hello china n f.writelines li f.close 檔案的內容 hello world hello china w...

python檔案的寫入

wirte 方法把字串寫入檔案,writelines 方法可以把列表中儲存的內容寫入檔案。f open hello.txt w encoding utf 8 li hello world n hello china n f.writelines li f.close 檔案的內容 hello worl...