2017 6 9 Python檔案讀寫的方法

2021-08-20 07:58:42 字數 1656 閱讀 2772

# 使用斜槓「/」: "c:/test.txt"… 不用反斜槓就沒法產生歧義了 

# 將反斜槓符號轉義: "c:\\test.txt"… 因為反斜槓是轉義符,所以兩個"\\"就表示乙個反斜槓符號

# file=open('d:\\jupyter\\test.txt')#

#file=open('d:/jupyter/test.txt')

#file=open('test.txt')#和程式在乙個同一路徑下

file=open('test.txt')

file.read()

'hi quincyqiang\nhow are you'
#模式描述

# # readline()是一行一行的讀

# readlines()是將文字檔案中所有行讀到乙個list中,文字檔案每一行是list的乙個元素。

# 優點:readline()可以在讀行過程中跳過特定行。 \

#第一種方法

file_1=open('test.txt')

file_2=open('output.txt','w')

while true:

line=file_1.readline()

print(line.strip())#取出換行

file_2.write(line)

if not line:

break

file_2.close()

hi quincyqiang

how are you

#第二種方法,使用for迴圈

file_2=open('output.txt','w')

for line in open('test.txt'):

print(line.strip())

file_2.write(line)

file_2.close()

hi quincyqiang

how are you

#第三種方法檔案上下文

檔案上下文管理器

with open('somefile.txt', 'r') as f:

data = f.read()

# iterate over the lines of the file

with open('somefile.txt', 'r') as f:

for line in f:

# process line

# write chunks of text data

with open('somefile.txt', 'w') as f:

f.write(text1)

f.write(text2)

...

# redirected print statement

with open('somefile.txt', 'w') as f:

print(line1, file=f)

print(line2, file=f)

2017 6 9 Python檔案讀寫的方法

使用斜槓 c test.txt 不用反斜槓就沒法產生歧義了 將反斜槓符號轉義 c test.txt 因為反斜槓是轉義符,所以兩個 就表示乙個反斜槓符號 file open d jupyter test.txt file open d jupyter test.txt file open test.t...

python讀檔案 python 檔案讀寫)

writefile test.txt 先自己寫乙個模組。這是乙個中文文件 第二行第三行 第四行 讀這個檔案有兩種方法 可以是f open test.txt 然後 f.read 這樣就讀取檔案裡的所有東西了。然後?f.close 就樣這個檔案便關閉了。還有就是f.readlines 一行一行的讀,這樣...

Python讀檔案 寫檔案

讀檔案 在相應的資料夾下建立乙個list.txt檔案。建立乙個包含檔案各行內容的列表 將要讀取的檔案的名稱儲存在變數filename中 filename list.txt with open filename as file obj 呼叫open 將乙個表示檔案及其內容的物件儲存到了變數file o...