“Python Lesen und Schreiben von Dateien” Code-Antworten

Python schreiben in die Datei

file = open(“testfile.txt”,”w”) 
 
file.write(“Hello World”) 
file.write(“This is our new text file”) 
file.write(“and this is another line.”) 
file.write(“Why? Because we can.”) 
 
file.close() 
Misty Macaw

Python schreiben in die Datei

# using 'with' block

with open("xyz.txt", "w") as file: # xyz.txt is filename, w means write format
  file.write("xyz") # write text xyz in the file
  
# maunal opening and closing

f= open("xyz.txt", "w")
f.write("hello")
f.close()

# Hope you had a nice little IO lesson
Psych4_3.8.3

Python öffnen und lesen Sie die Datei mit

with open('pagehead.section.htm','r') as f:
    output = f.read()
Good Goshawk

Python -Datei lesen

fin = open("NAME.txt", 'r')
body = fin.read().split("\n")
line = fin.readline().strip()
Bewildered Baboon

Lesen Sie Dateien und schreiben Sie in andere Dateien Python

import sys
import glob
import os.path

list_of_files = glob.glob('/Users/Emily/Topics/*.txt') #500 files

for file_name in list_of_files:
    print(file_name)

    # This needs to be done *inside the loop*
    f= open(file_name, 'r')
    lst = []
    for line in f:
       line.strip()
       line = line.replace("\n" ,'')
       line = line.replace("//" , '')
       lst.append(line)
    f.close()

    f=open(os.path.join('/Users/Emily/UpdatedTopics',
    os.path.basename(file_name)) , 'w')

    for line in lst:
       f.write(line)
    f.close()
Joyous Jellyfish

Python Lesen und Schreiben von Dateien

'''
You can read and write in files with open()
'r' = read
'w' = write (overwrite)
'a' = append (add)

NOTE: You can use shortened 'file.txt' if the file is in the same
directory (folder) as the code. Otherwise use full file adress.
'''

myFile = open('file.txt', 'r') # Open file in reading mode
print(myFile.read()) # Prints out file
myFile.close() # Close file

myNewFile = open('newFile.txt', 'w') # Overwrites file OR creates new file
myNewFile.write('This is a new line') # Adds line to text
myNewFile.close()

file = open('newFile.txt', 'a') # Opens existing newFile.txt
file.write('This line has been added') # Add line (without overwriting)
file.close()
Ninja Penguin

Ähnliche Antworten wie “Python Lesen und Schreiben von Dateien”

Fragen ähnlich wie “Python Lesen und Schreiben von Dateien”

Weitere verwandte Antworten zu “Python Lesen und Schreiben von Dateien” auf Python

Durchsuchen Sie beliebte Code-Antworten nach Sprache

Durchsuchen Sie andere Codesprachen