Python File Write
Zápis do existujícího souboru
Chcete-li zapisovat do existujícího souboru, musíte do
open()
funkce přidat parametr:
"a"
- Append - přidá se na konec souboru
"w"
- Write - přepíše jakýkoli existující obsah
Příklad
Otevřete soubor "demofile2.txt" a připojte obsah k souboru:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f =
open("demofile2.txt", "r")
print(f.read())
Příklad
Otevřete soubor "demofile3.txt" a přepište obsah:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
Poznámka: metoda "w" přepíše celý soubor.
Vytvořte nový soubor
Chcete-li vytvořit nový soubor v Pythonu, použijte open()
metodu s jedním z následujících parametrů:
"x"
- Vytvořit - vytvoří soubor, vrátí chybu, pokud soubor existuje
"a"
- Připojit - vytvoří soubor, pokud zadaný soubor neexistuje
"w"
- Write - vytvoří soubor, pokud zadaný soubor neexistuje
Příklad
Vytvořte soubor s názvem "myfile.txt":
f = open("myfile.txt", "x")
Výsledek: Vytvoří se nový prázdný soubor!
Příklad
Vytvořte nový soubor, pokud neexistuje:
f = open("myfile.txt", "w")