Skip to content
Sign upLog in
← Back to Community

managing external files in python

Profile icon
xolyon

Ok so its quite simple with python

to open a file you do this

file_example = open("[filename]", "operation")
here are the operations:

r - read contents of a file w - write on contents of a file (more like append) wb - write bits on contents of a file rb - read bits on contents of a file

with the following I can do this:
disclaimer but opening a new file which doest exists will simply create one and I prefer using .txt files for this

file1 = open("meme.txt","r") fileRead = file1.read() print(fileRead)

we can also print each individual line like this:

file1 = open("gucci.txt", "r") mwmw = file1.readlines() # in parameters is how many lines you wish to print , leave blank if you wanna read all for x in mwmw: print(x)

to convert file data into something more your taste:

file1 = open("gucci.txt", "r") mwmw = file1.read() gucci = int(mwmw) #type you want #there must be no spaces or anything like lines in your file if you want proper print(Gucci)

unfortunately to delete the contents requires manual deletion (to select all do ctrl + a)

but here's a handy script if you really need it:

import os os.remove("gucci.txt") print("File Removed!")

cant import os? or only wish to delete contents of a file?
no problem here is a handy script!

file = open("gucci.txt","r+") file.truncate(0) file.close()

IMPORTANT

you don't need to do this but to stop silly errors once you have finished with your file just use

fileName.close() to finish`
Thanks for sticking around! if this helped then give updoot

Voters
Profile icon
AarezKhan
Profile icon
VanceBakalov
Profile icon
Bently
Profile icon
awodeay1
Profile icon
xolyon
Comments
hotnewtop
Profile icon
xolyon

@CodingCactus
@epicman702
here ya go

Profile icon
CodingCactus

@xolyon
why have I been summoned?

Profile icon
xolyon

@CodingCactus
I invited another guy to project and he didn't know how to do this so i made this, i figured i might as well summon u just in case, btw i made storyline and everything on project u might wanna check it out

Profile icon
CodingCactus

@xolyon
ok, I don't know how to use files either, so I'll give it a read after school