“Jak wymienić słowo w pliku tekstowym za pomocą Pythona” Kod odpowiedzi

Python Znajdź i wymień ciąg w pliku

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)
Frantic Fish

Jak wymienić słowo w pliku tekstowym za pomocą Pythona

# How to replace a word in a text file

filename = "sample1.txt"
# SAMPLE1.TXT
# Hello World!
# I am a human.

with open(filename, 'r+') as f:
    text = f.read()
    text = re.sub('human', 'cat', text)
    f.seek(0)
    f.write(text)
    f.truncate()

# SAMPLE1.TXT
# Hello World!
# I am a cat.
Alert Alligator

Odpowiedzi podobne do “Jak wymienić słowo w pliku tekstowym za pomocą Pythona”

Pytania podobne do “Jak wymienić słowo w pliku tekstowym za pomocą Pythona”

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu