溫馨提示×

python中的write函數(shù)與read函數(shù)的配合使用

小樊
85
2024-08-21 06:03:28
欄目: 編程語言

在Python中,可以使用write函數(shù)來向文件中寫入數(shù)據(jù),然后使用read函數(shù)來讀取文件中的數(shù)據(jù)。下面是一個簡單的示例:

# 寫入數(shù)據(jù)到文件中
with open('example.txt', 'w') as f:
    f.write('Hello, World!')

# 從文件中讀取數(shù)據(jù)
with open('example.txt', 'r') as f:
    data = f.read()
    print(data)

在這個示例中,首先使用write函數(shù)將字符串’Hello, World!'寫入到名為example.txt的文件中。然后使用read函數(shù)從文件中讀取數(shù)據(jù),并將讀取到的數(shù)據(jù)打印出來。

0