溫馨提示×

Ubuntu Python如何進行文件操作

小樊
35
2025-06-21 10:28:48
欄目: 編程語言

在Ubuntu上使用Python進行文件操作,你可以使用內置的open()函數來打開文件,然后使用文件對象的方法來進行讀寫等操作。以下是一些基本的文件操作示例:

  1. 打開文件:
# 打開一個文件用于讀取
file = open('example.txt', 'r')

# 打開一個文件用于寫入(如果文件存在,它會被覆蓋)
file = open('example.txt', 'w')

# 打開一個文件用于追加(如果文件存在,新的內容會被添加到文件末尾)
file = open('example.txt', 'a')
  1. 讀取文件:
# 讀取整個文件內容
content = file.read()

# 逐行讀取文件內容
for line in file:
    print(line)

# 讀取指定數量的字符
content = file.read(100)
  1. 寫入文件:
# 寫入字符串到文件
file.write('Hello, World!\n')

# 寫入多行到文件
file.writelines(['Line 1\n', 'Line 2\n', 'Line 3\n'])
  1. 關閉文件:
file.close()

為了避免忘記關閉文件,可以使用with語句,它會在代碼塊執行完畢后自動關閉文件:

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

# 文件在這里已經關閉了
  1. 檢查文件是否存在:
import os

if os.path.exists('example.txt'):
    print('File exists.')
else:
    print('File does not exist.')
  1. 獲取文件大?。?/li>
file_size = os.path.getsize('example.txt')
print(f'The size of the file is {file_size} bytes')
  1. 列出目錄中的所有文件:
files = os.listdir('/path/to/directory')
for file in files:
    print(file)

這些是Python中進行文件操作的一些基本方法。根據你的需求,你可能需要使用更多的函數和方法來處理文件。記得在操作文件時始終要注意文件的打開模式,以免意外地覆蓋或損壞文件。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女