“Python Reading and Writing Fichiers” Réponses codées

python écrivez dans le fichier

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 écrivez dans le fichier

# 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 ouvrir et lire le fichier avec

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

lecture de fichiers python

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

Lisez les fichiers et écrivez dans un autre fichier 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 Reading and Writing Fichiers

'''
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

Réponses similaires à “Python Reading and Writing Fichiers”

Questions similaires à “Python Reading and Writing Fichiers”

Plus de réponses similaires à “Python Reading and Writing Fichiers” dans Python

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code