Maximum efficiency and Ultimate mastery of teaching has been shown in this video! You present your tutorials like a rabbi who read the scripture his whole life! Magnificent!
Thank You Corey! You are a talented and gifted Tutor. I have watched over 50 python tutorials and yours are the best example of what I have found on TH-cam.
@@Laevatei1nn Once u read 100 elements, curser will move to 101. If we just read once outside the loop where u read only once and length does not decrease and loop run infinitely. if you read inside a loop, curser keeps moving after every loop and once if it finds no content to read u will get zero length data, so the loop breaks.
The way this videos are systematically put together makes everything so easy to understand. Watching your videos is so helpful and motivating . Thank you Corey!
Really helpful explanation of read & writing to files. This was quick and succinct. Helped me understand a few things that others don't cover. I love how you covering just the right stuff.
i aspire to be this interested. at the mo the only time i look up corey's videos is 3 hours before an exam when i timely realize that i have not ~bothered~ to learn a seemingly harmless but deadly aspect of the syllabus.
This was incrediby clear and useful. I actually started predicting what was going to happen not because it was obvious but because you explained it so well. Instant subscribe.
What a hell.is that rb wb. Its been long time watching python tutoriels and never see reading and writing in files with binary system. Corey you are God of python. Really you deserve Million thanks. Please keep going and uploading new videos.
Thank you so much!!!! Your video is extraordinary. You explain these concepts clearly and thoroughly, in a very engaging way with practical examples. You made me understand this topic very quickly. Thanks again!
My Notes for this video. You can comment out all of it and uncomment and run one function at a time to revise what Corey has taught us: # While opening a file we can specify whether we are opening the file for 'reading', 'writing', 'reading & writing' or 'appending' # If we don't specify anything, it defaults to 'reading' # f = open('text.txt', 'w') # Opens a file for writing # f = open('text.txt', 'r+') # Opens a file for reading & writing # f = open('text.txt', 'a') # Opens a file for appending # Opens a file for reading f = open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') print(f.name) # Returns the name of the open file print(f.closed) # Returns whether the file associated with the variable is closed print(f.mode) # Returns the mode in which it was opened i.e. 'r', 'w', 'r+', 'a' # All files opened using an open() command need to be closed explicitly after their use is complete. If this is not done , we can end up with leaks that cause us to run over the maximum allowed file descriptors on the system and our app can throw an error. f.close() # We can avoid this problem with a context manager as below # The below 'with open()' command will close the file as soon as the code has finished running or an error is thrown with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: # Code goes here pass # This produces the error "ValueError: I/O operation on closed file."" # print(f.read()) with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: # This just reads all lines in the file text_file_contents = text_file.read() print(text_file_contents) with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: # This returns a list that contains all lines in the file text_file_contents = text_file.readlines() print(text_file_contents) with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: # This returns a line of text (not a list) at a time # The first time we print .readline() it returns the first line text_file_contents = text_file.readline() print(text_file_contents) # The second time we print .readline() it returns the second line text_file_contents = text_file.readline() print(text_file_contents) with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: # This returns a line of text (not a list) at a time # The first time we print .readline() it returns the first line # Putting an 'end = '' in the return or print statement removes the newline between each result text_file_contents = text_file.readline() print(text_file_contents, end='') # The second time we print .readline() it returns the second line # Putting an 'end = '' in the return or print statement removes the newline between each result text_file_contents = text_file.readline() print(text_file_contents, end='') # The above methods take a lot of storage as lines get stored in memory # Iterating over lines in a file avoid this with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: for line in text_file: print(line, end='') with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: # Passing a number to the .read() command preads just that number of characters # The first time this is run, a 10 characters will be read and printed text_file_contents = text_file.read(10) print(text_file_contents, end='') # It returns '#1) This is' # The second time this is run, the next 10 characters will be read and printed text_file_contents = text_file.read(10) print(text_file_contents, end='') # '1) This is a test fi' # The same line is extended (without introducing a new line or a new returned value) # When we reach the end of the file, read just reads what is left and returns an empty string for the rest of it text_file_contents = text_file.read(1000) print(text_file_contents, end='') # The below code will print out the entire code with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: size_to_read = 10 text_file_contents = text_file.read(size_to_read) while len(text_file_contents) > 0: print(text_file_contents, end='') text_file_contents = text_file.read(size_to_read) # with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: size_to_read = 10 text_file_contents = text_file.read(size_to_read) while len(text_file_contents) > 0: # The '#' symbol in the output marks the chunks that were printed in each iteration print(text_file_contents, end='#') text_file_contents = text_file.read(size_to_read) with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: size_to_read = 10 text_file_contents = text_file.read(size_to_read) # The 'filename.tell()' returns the position of the file till where we've read until now # This returns 10, since we've read 10 characters print(text_file.tell()) text_file_contents = text_file.read(size_to_read) # This returns 20, since we've read 10 more characters (10+10=20) print(text_file.tell()) with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: size_to_read = 10 # Reads the first 10 characters. Read position set to 10 text_file_contents = text_file.read(size_to_read) print(text_file.tell()) # Prints 10 # Reads the next 10 characters. Read position set to 10+10=20 text_file_contents = text_file.read(size_to_read) print(text_file.tell()) # Prints 20 # filename.seek() sets the read position to whatever character we set it to. Here set to 0. text_file.seek(0) # Sets the read position to 0 print(text_file.tell()) # Prints 0 # Reads the first 10 characters. Read position set to 10 text_file_contents = text_file.read(size_to_read) print(text_file.tell()) # Prints 10
# If we try to write to a file that is opened for reading. An error is produced. # Error = 'io.UnsupportedOperation: not writable' # with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: # text_file.write('Test') # If a file with this name doesn't already exist. It will be created. # If a file does exist, it will be overwritten with open('C:/#Personal/Coding Projects/Proj1/Py edn/text2.txt', 'w') as text_file: text_file.write('Test') # If you don't want to overwrite a file, use an 'append' setting by passing a lowercase a with open('C:/#Personal/Coding Projects/Proj1/Py edn/text2.txt', 'a') as text_file: text_file.write('Test') with open('C:/#Personal/Coding Projects/Proj1/Py edn/text2.txt', 'w') as text_file: text_file.write('Test') # File contains: 'Test' # filename.seek(position) sets the write position to the number we pass in text_file.seek(0) # If we now write something. It will be written from the newly set position. # It will overwrite anything in its path for as many characters it need to overwrite text_file.write('LN') # File contains: 'LNst'. # The first 2 characters from position 0 were overwritten because it was required # Copying from one file to another, line by line # This can't be done for image files. It shows an error. Invalid start byte. Copying an image file would require opening it in binary mode. We would be reading/writing bytes instead of text. with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: with open('C:/#Personal/Coding Projects/Proj1/Py edn/textcopy.txt', 'w') as copy_file: for line in text_file: copy_file.write(line) # To read binary we change open(filename,'r') to open(filename, 'rb') # To read binary we change open(filename,'w') to open(filename, 'wb') # The below code with these changes, can copy an image file with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'rb') as text_file: with open('C:/#Personal/Coding Projects/Proj1/Py edn/textcopy.txt', 'wb') as copy_file: for line in text_file: copy_file.write(line) # Copying a file using chunks instead of line by line is better. This can be done by using the .read function we've studied above with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file: with open('C:/#Personal/Coding Projects/Proj1/Py edn/textcopy.txt', 'w') as copy_file: chunk_size = 10 chunk = text_file.read(chunk_size) while len(chunk) > 0: copy_file.write(chunk) chunk = text_file.read(chunk_size)
Now I'm in a confusion that weather the creator of python or its this guy, "Corey Schafer" , made python so simple. Thank you sir for your awesome explanation
Wow. I've been trying to learn certain concepts in python for a while now and I've come to the conclusion that your videos are beyond amazing and super helpful. literally couldn't be more grateful
Very clean and too the point tutorial. Thanks for this easy to grab explanation. I'm quite comfortable now as far as basic file operations are concerned.
This man deserves a knighthood. In the name of the Warrior I charge you Ser Corey Schafer to be brave. In the name of the Father I charge you to be just. In the name of the teacher I charge you to educate the masses. In the name..... Arise Ser Corey Schafer:)
user_nickname = "This man" user_title = " Ser " user_name = "Corey Schafer " action_prog1 = "to be brave" action_prog2 = "to be just" action_prog3 = "to educate the masses" prize = "a knighthood" supernatural_being1 = "the Warrior" supernatural_being2 = "the Father" important_person = "the teacher" speech = user_nickname + " deserves " + prize + ". " + "In the name of " + supernatural_being1 + " I charge you " + user_title + user_name + action_prog1 +". " + "In the name of " + supernatural_being2 + " I charge you " + action_prog2 +". " + "In the name of " + important_person + " I charge you " + action_prog3 +". " + "In the name..... " + "Arise" + user_title + user_name + ":)" print(speech)
I've just come across this and you are about to become my saviour because I'm about 10 hours behind on my controlled assessment and have no idea what I'm doing
I agree with Airth. Your python series is awesome. Your videos are great. I think its the depth you go into, the many different ways to do it, and the way you should do it. Oh and so much "energy" and "flow" in the videos.
Very simple to understand and just filtering out the important bits alone! If you do have a dedicated tutorial in udemey, I would love to subscribe! Keep creating Sir Corey! :P :D
@Corey Schafer 1_ Thank you for this manual. 2_ Don't forget to add that a common error may occur when you give the file name with the directory, basically its when Python will interpret the directory address as string, which will cause a problem with escape characters
*Summary of the Video:* *file.open("path", "mode")* --> opens the file in respective mode. *Modes* *'r'* --> for read file contents. *'w'* --> for writing to file. *'a'* --> for eppending file contents. *'r+'* --> for reading and writing *'b'* --> to open file in binary mode (for reading images) *Note:* We can use different modes together like 'rb' can be used for reading a binary file. *file.close()* --> closes a file. *file.mode* --> returns the mode the file was opened in. *file.name* --> returns the name of the file as a string. For effiency we use context managers. The automatically close the file once we are out of the context manager the file was opened in. We can open a file using a context manager and assign the result to a variable. We can use this variable inside the context manager. *Reading from files* *file.read([size])* --> This method typically reads the entire content of the file. But if provided with a size (which is an optional argument), it can read 'size' number of characters. If used repeatedly, it always continues from the next character to the last character it read. *file.readlines()* --> returns a list of all of the lines of the file. (adds to represent start of next line) *file.readline()* --> Reads a single line from the file. If called repeatedly, it can read all of the lines one by one. *Note:* A file is treated as an iterable in python. This simply means that we can iterate over the lines of the file using a for loop (like we would loop over the elements of a list). We can also use a while loop to iterate over the contents of a file. We do this by specifing the number of characters we want to read at each iteration. Then we repeatedly used file.read() method to read the characters until there is nothing left to read. _size = 10_ _fileContents = file.read(size)_ _while len(fileContents) > 0:_ # while the length of what we have read is not 0, continue reading _print(fileContents, end=''')_ _fileContents = file.read(size)_ The *tell()* and *seek()* methods. Just like arrays, files are also zero-indexed. This means that the first element has a index of 0, second element has an index of 1 and so on. Python uses a pointer to keep track of where it should be reading from and writing to the files. In the start this point is at 0. As we read from the file, this pointer moves. For example, if we read 10 characters, this means that the pointer is not at index 10; it is going to read the 11th character next. It read from the 1st till the 10th characters (10th inclusive). Similiar mechanism is used for writing to files. *file.tell()* --> returns the position of where the pointer is. *file.seek(new_position)* --> sets the pointer to the specified position. *Writing to Files* The file should be opened in the 'write' mode. (mode = 'w'). *file.write(content)* --> writes the contents to the file. *Note:* trying to write to a file that does not exist will first create the file and then perform the writing operation. You can use nested (one in another) context managers to simultaneously read from a file and write to another file. Here is the code: _with open("readFilePath", 'r') as readFile:_ _with open("writeFilePath", 'w') as writeFile:_ _for line in readFile: _writeFile.write(line) You can also do: _with open("readFilePath", 'r') as readFile:_ _with open("writeFilePath", 'w') as writeFile:_ _writeFile.write(readFile.read())_ I hope this helps!
Love your Python (and other) videos - some of the best coding tutorials on TH-cam. Very clear, detailed, in-depth explanations that get right to the point. Great work! Ideas for future tutorials: -Much more on classes, including composition, polymorphism, when to use classes vs other data structures, etc. -Enums and when to use them (introduced recently in Python) -Examples of when to choose different data structures and how to implement each. - Oauth and working with APIs through Python -PDB / debugging -Testing web apps -Selenium and Python -Beautiful Soup -Pytest -Pylint -TDD -Encapsulation / structuring code in python effectively -Advanced namespaces / modules / packages -Flask (advanced or in-depth, eg explaining the app context and how working with Flask blueprints is different from the usual modules and if ‘__name__’ == ‘__main__’ - Intermediate/ Advanced object oriented programming - Refactoring and code smells - Functional programming - Advanced Sublime Text - Workflow, eg syncing dev environments across different platforms, version control for dotfiles, etc. - Productivity tips - Design patterns - Medium/low-level networking and web programming with Python (understanding HTML headers, session objects / cookies, HTTP protocol, servers, AJAX and REST APIs, etc. - Setting up a personal web server, mail server, file server, owncloud, etc. - Executing JavaScript with Python - Setting up a LAN / basic home networking - Scripting and automation tips/ideas/anything - MongoAlchemy and/or Pymongo and/or SQLAlchemy - Building a web app with Python/Flask backend and JavaScript/Angular frontend - Advanced regular expressions (maybe covered in your newest video)-e.g., escaping regex strings - String templating, text replacement, etc. - Collections module - Modules that are useful or should be in the standard library but are not - Advanced / in-depth primitive operations, e.g. string and dict methods. Thank you!
How do I write and read a file simultaneously .I tried to do but after every read operation its simultaneously writing the same content the no of times i run the prog which is not what i want .Please help !! Thank you !
Well. Hope this isn't too late 😅 But you need to control the file pointer on the open file object, when you open a file in r+ or w+ mode the file pointer starts from the top of the file (0) so you'll need to get it to the end of the file before writing new data
for line in f: how does it take in one line like we havent specified anything line why doesnt line iterate through each character . how does it iterate through each line can someone please help me? :)
@@vaibhavdumaga7229 Same issue here. But I think it is in-built and so the for-loop function automatically knows. From documentation, it says that some file objects are iterable, meaning when used in a loop, it automatically "knows" how to go to the next item in the file object.Don't fully understand, but it seems to be in built so it's automatic. See for yourself here under iterable: docs.python.org/3/glossary.html#term-iterable
This helped a lot actually, thanks. I started learning Python a few days ago, and decided to create a game (never done coding before). I was having an issue with trying to figure out how to define a variable to a specific line (readline; didn't know that at the time), as a means of tracking the progress and associated flags as the player goes through the game. (An RPG; so far working systems, not all fully integrated: Main Menu, Combat Module, Character Class + Character Power Choosers, and Class for Enemies and scaling stats based on level) If any of you were wondering how to do that, or needed reinforcement for it: I created (using another, not shown, while loop + function), gameSave.txt file, and defined values to put into it (writing it into existence) And for loading I use the below to pull the values from that written file, and save them as variables as it runs ############# DELETE THE # IF YOU ARE TRYING TO RUN THIS IN A FILE, AND MAKE SURE TO CREATE A FILE CALLED gameSave.txt and put stuff on first 3 lines####### #################DELETE EVERYTHING TO THE RIGHT OF A # THAT IS MY ANNOTATION EXPLAINING IT global pclevel #define the variables as with the global tag, this helps avoid issues where you can't set a value to a variable while it is within a function (might not be needed in some cases) global pcxp global pcname pclevel = '' #this is empty in the middle, two ' ergo empty variable pcxp = '' pcname = '' with open('gameSave.txt', 'r') as g: #defined g as the term to open the file, as it is shorter and I'm feeling lazy after awhile gsave = g #gsave = g, I didn't use gsave here but figured it is best to store the values as it is a small file, would probably not recommend unless you intend to use it later pclevel = g.readline() #I stored the values in lines 1-3, and so set a value to each based on sequential readline, which is read as g (where we defined open('gameSave.txt', 'r')).readline() pcxp = g.readline() #gets the second line pcname = g.readline() #gets the third line print(pclevel) print(pcxp) print(pcname) #the above 'open' redefines the variables to the values that are stored within each line of the file, in sequential order, and then printing that variable will print out the stored information #worth noting, if you wanted to do say print('My name is ' + pcname + ' and my level is ' + pclevel) #you would need to do a str(pclevel) for example, to convert the stored number into a string; attempting to print an integer + a str won't work #i.e. print('My name is ' + str(pcname) + ' and my level is ' + str(pclevel)) #never hurts to be safe, the name SHOULD be stored as a str, but idk maybe you're R2D2 or something
Great tuts. I assume this is for python 3? I tried to do this in 2.7 and it doesn't seem to like the syntax with the "end". I guess I should start transition to 3. Overall like your style of teaching. Edit- I got it to work if in python 2.7, you have do an import -> from __future__ import print_function
Sorry for the late reply. Yes, this is Python 3. It took me a long time to transition over too, but since it is the recommended version now it is a good idea to switch over if possible.
Amazing.. am loving Python even more now ! Please dd more tutorials to Files on files like reading from IO, memory, csv files, or extracting data from unstructured format .
Thanks, Alex! I really appreciate that. I haven't recorded the tmp and in-memory files video yet, but I still plan on putting one together in the near future after I get some other videos in my list finished up and published. Thanks again!
No gimmicky loud background music or talking like he's some badass hacker...just clearly explained lessons that are easy to understand. Awesome work!
when ur actually a badass hacker, but act like a normal rational person
what tutorial have you seen where the guy doing it talks like a "baddass hacker" I want to watch that
@@stratosvagiannis5140Lul I’m also curious
Yeah, propper real G Nigga :D I is to watch this vid 100 times @ speed 0.25
Maximum efficiency and Ultimate mastery of teaching has been shown in this video! You present your tutorials like a rabbi who read the scripture his whole life! Magnificent!
Thank You Corey! You are a talented and gifted Tutor. I have watched over 50 python tutorials and yours are the best example of what I have found on TH-cam.
on 23:38, how does the last line of the while loop prevents infinite loop?
@@Laevatei1nn Once u read 100 elements, curser will move to 101. If we just read once outside the loop where u read only once and length does not decrease and loop run infinitely. if you read inside a loop, curser keeps moving after every loop and once if it finds no content to read u will get zero length data, so the loop breaks.
You are even better than the teachers in udemy . They don't know about being fluent.
I'm watching this tutorial meanwhile saw ur comment which is 5 yrs ago. He really explains things simply and easy to understand
BEST PYTHON TUTORIALS!!!!!
ya trueee he is awesome
Dude, I'm in love with your python series. Keep up the amazing work.
+Airth Thanks! I appreciate that. Glad you find them useful.
what version of python do you have in this video
please reply
So am I. There are good instructors of different languages. Corey is the guy in python. Thanks Corey.
The way this videos are systematically put together makes everything so easy to understand.
Watching your videos is so helpful and motivating .
Thank you Corey!
Really helpful explanation of read & writing to files. This was quick and succinct. Helped me understand a few things that others don't cover. I love how you covering just the right stuff.
Yours are some of the best python tutorials I've found on TH-cam. No bs. Very well explained. Cheers mate
Never saw a mentor like you before.
You are the one who teaches fellows like me for free.
Thank you so much sir.
You all tutorials are stright forward and cover all aspect of a specific topic. Thank you for this channel.
these are better than my 2 hours lectures... My professor sucks so much at teaching python. These are amazing and a life saver!
Have u graduated already?
okay i'm at a point where i watch corey's videos just after waking up...
for fun.
U a anime boy?
Same here
i aspire to be this interested.
at the mo the only time i look up corey's videos is 3 hours before an exam when i timely realize that i have not ~bothered~ to learn a seemingly harmless but deadly aspect of the syllabus.
i wish XD
are u a masochist
Simply the BEST python tutor ever...truly life saving! And the picture of your dog just made my day 100% better!
Huge thanks for all!!
This video is so well explained. I’m a beginner and am able to follow everything perfectly!
although I am discovering this 8 years after I still find it very awesome. Keep up the good work man
You're a truly talented teacher. Better than any online course I've tried so far.
Thanks! I appreciate that.
I rarely comment a video, but thank you Corey. You earn yourself a subscriber for life 😊.
This was incrediby clear and useful. I actually started predicting what was going to happen not because it was obvious but because you explained it so well. Instant subscribe.
You have the clearest, best explained videos on Python. Great job.
Brilliant, A good teacher can make you remember concepts with ease. I am delighted to gain from your teachings. Thanks a ton.
Best python video tutorial on the Internet, bar none.
Don't @ me.
Sir you make the best tutorials of python! I'm sure not even the paid stuff can beat this.
This chanel is something that i will watch all the python tutorials of, and will come back from time to time to refresh what i've learned, thank you.
2 years Later: It's still relevant God damn it !! Thanks Corey
i think i got enough to get started on my first python project but gunna keep watching one a day because they are soooo good!
This really helped me understand how to read and write to files. Thank you for your time and expertise.
What a hell.is that rb wb. Its been long time watching python tutoriels and never see reading and writing in files with binary system. Corey you are God of python. Really you deserve Million thanks. Please keep going and uploading new videos.
Thank you so much!!!! Your video is extraordinary. You explain these concepts clearly and thoroughly, in a very engaging way with practical examples. You made me understand this topic very quickly. Thanks again!
8 years since he uploaded this video and I'm here learning a lot hahah. Thanks, man. Great video!
These must be the classes from the Corey Schafer University.
Absolutely fantastic videos !
Probably the best and most detailed tutorials out there.
My Notes for this video. You can comment out all of it and uncomment and run one function at a time to revise what Corey has taught us:
# While opening a file we can specify whether we are opening the file for 'reading', 'writing', 'reading & writing' or 'appending'
# If we don't specify anything, it defaults to 'reading'
# f = open('text.txt', 'w') # Opens a file for writing
# f = open('text.txt', 'r+') # Opens a file for reading & writing
# f = open('text.txt', 'a') # Opens a file for appending
# Opens a file for reading
f = open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r')
print(f.name) # Returns the name of the open file
print(f.closed) # Returns whether the file associated with the variable is closed
print(f.mode) # Returns the mode in which it was opened i.e. 'r', 'w', 'r+', 'a'
# All files opened using an open() command need to be closed explicitly after their use is complete. If this is not done , we can end up with leaks that cause us to run over the maximum allowed file descriptors on the system and our app can throw an error.
f.close()
# We can avoid this problem with a context manager as below
# The below 'with open()' command will close the file as soon as the code has finished running or an error is thrown
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
# Code goes here
pass
# This produces the error "ValueError: I/O operation on closed file.""
# print(f.read())
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
# This just reads all lines in the file
text_file_contents = text_file.read()
print(text_file_contents)
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
# This returns a list that contains all lines in the file
text_file_contents = text_file.readlines()
print(text_file_contents)
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
# This returns a line of text (not a list) at a time
# The first time we print .readline() it returns the first line
text_file_contents = text_file.readline()
print(text_file_contents)
# The second time we print .readline() it returns the second line
text_file_contents = text_file.readline()
print(text_file_contents)
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
# This returns a line of text (not a list) at a time
# The first time we print .readline() it returns the first line
# Putting an 'end = '' in the return or print statement removes the newline between each result
text_file_contents = text_file.readline()
print(text_file_contents, end='')
# The second time we print .readline() it returns the second line
# Putting an 'end = '' in the return or print statement removes the newline between each result
text_file_contents = text_file.readline()
print(text_file_contents, end='')
# The above methods take a lot of storage as lines get stored in memory
# Iterating over lines in a file avoid this
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
for line in text_file:
print(line, end='')
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
# Passing a number to the .read() command preads just that number of characters
# The first time this is run, a 10 characters will be read and printed
text_file_contents = text_file.read(10)
print(text_file_contents, end='') # It returns '#1) This is'
# The second time this is run, the next 10 characters will be read and printed
text_file_contents = text_file.read(10)
print(text_file_contents, end='') # '1) This is a test fi'
# The same line is extended (without introducing a new line or a new returned value)
# When we reach the end of the file, read just reads what is left and returns an empty string for the rest of it
text_file_contents = text_file.read(1000)
print(text_file_contents, end='')
# The below code will print out the entire code
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
size_to_read = 10
text_file_contents = text_file.read(size_to_read)
while len(text_file_contents) > 0:
print(text_file_contents, end='')
text_file_contents = text_file.read(size_to_read)
#
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
size_to_read = 10
text_file_contents = text_file.read(size_to_read)
while len(text_file_contents) > 0:
# The '#' symbol in the output marks the chunks that were printed in each iteration
print(text_file_contents, end='#')
text_file_contents = text_file.read(size_to_read)
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
size_to_read = 10
text_file_contents = text_file.read(size_to_read)
# The 'filename.tell()' returns the position of the file till where we've read until now
# This returns 10, since we've read 10 characters
print(text_file.tell())
text_file_contents = text_file.read(size_to_read)
# This returns 20, since we've read 10 more characters (10+10=20)
print(text_file.tell())
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
size_to_read = 10
# Reads the first 10 characters. Read position set to 10
text_file_contents = text_file.read(size_to_read)
print(text_file.tell()) # Prints 10
# Reads the next 10 characters. Read position set to 10+10=20
text_file_contents = text_file.read(size_to_read)
print(text_file.tell()) # Prints 20
# filename.seek() sets the read position to whatever character we set it to. Here set to 0.
text_file.seek(0) # Sets the read position to 0
print(text_file.tell()) # Prints 0
# Reads the first 10 characters. Read position set to 10
text_file_contents = text_file.read(size_to_read)
print(text_file.tell()) # Prints 10
# If we try to write to a file that is opened for reading. An error is produced.
# Error = 'io.UnsupportedOperation: not writable'
# with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
# text_file.write('Test')
# If a file with this name doesn't already exist. It will be created.
# If a file does exist, it will be overwritten
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text2.txt', 'w') as text_file:
text_file.write('Test')
# If you don't want to overwrite a file, use an 'append' setting by passing a lowercase a
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text2.txt', 'a') as text_file:
text_file.write('Test')
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text2.txt', 'w') as text_file:
text_file.write('Test') # File contains: 'Test'
# filename.seek(position) sets the write position to the number we pass in
text_file.seek(0)
# If we now write something. It will be written from the newly set position.
# It will overwrite anything in its path for as many characters it need to overwrite
text_file.write('LN') # File contains: 'LNst'.
# The first 2 characters from position 0 were overwritten because it was required
# Copying from one file to another, line by line
# This can't be done for image files. It shows an error. Invalid start byte. Copying an image file would require opening it in binary mode. We would be reading/writing bytes instead of text.
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
with open('C:/#Personal/Coding Projects/Proj1/Py edn/textcopy.txt', 'w') as copy_file:
for line in text_file:
copy_file.write(line)
# To read binary we change open(filename,'r') to open(filename, 'rb')
# To read binary we change open(filename,'w') to open(filename, 'wb')
# The below code with these changes, can copy an image file
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'rb') as text_file:
with open('C:/#Personal/Coding Projects/Proj1/Py edn/textcopy.txt', 'wb') as copy_file:
for line in text_file:
copy_file.write(line)
# Copying a file using chunks instead of line by line is better. This can be done by using the .read function we've studied above
with open('C:/#Personal/Coding Projects/Proj1/Py edn/text.txt', 'r') as text_file:
with open('C:/#Personal/Coding Projects/Proj1/Py edn/textcopy.txt', 'w') as copy_file:
chunk_size = 10
chunk = text_file.read(chunk_size)
while len(chunk) > 0:
copy_file.write(chunk)
chunk = text_file.read(chunk_size)
thanks for this ur a legend
Really, you`re a legend
Thx a lot, you saved me a bunch of time
Thanks alot! that was super helpful
Underrated Comment
My brother , Thank you ! You are a great educator of our time !!!!
Now I'm in a confusion that weather the creator of python or its this guy, "Corey Schafer" , made python so simple. Thank you sir for your awesome explanation
Wow. I've been trying to learn certain concepts in python for a while now and I've come to the conclusion that your videos are beyond amazing and super helpful. literally couldn't be more grateful
Very clean and too the point tutorial. Thanks for this easy to grab explanation. I'm quite comfortable now as far as basic file operations are concerned.
I can't stop watching these tutorials! Thanks, man!
Thanks! I'm happy to hear you're finding them useful.
Your puppy is ADORABLE!! Thanks for the video
i thought i know how to read and write file, after watching this series i now know how to write and read awesome files. thanks so much
This man deserves a knighthood.
In the name of the Warrior I charge you Ser Corey Schafer to be brave.
In the name of the Father I charge you to be just.
In the name of the teacher I charge you to educate the masses.
In the name.....
Arise Ser Corey Schafer:)
user_nickname = "This man"
user_title = " Ser "
user_name = "Corey Schafer "
action_prog1 = "to be brave"
action_prog2 = "to be just"
action_prog3 = "to educate the masses"
prize = "a knighthood"
supernatural_being1 = "the Warrior"
supernatural_being2 = "the Father"
important_person = "the teacher"
speech = user_nickname + " deserves " + prize + ".
" + "In the name of " + supernatural_being1 + " I charge you " + user_title + user_name + action_prog1 +".
" + "In the name of " + supernatural_being2 + " I charge you " + action_prog2 +".
" + "In the name of " + important_person + " I charge you " + action_prog3 +".
" + "In the name.....
" + "Arise" + user_title + user_name + ":)"
print(speech)
?
@@ДжонШепард-ы8й I guess that works
yeah in the name of......
Ur name looks little bit girly so did you forget in the name of husband
Man , these videos are Really good.. The author focused on actual real time use cases and tutorial makes so much sense.. Great Job
Thank you Corey for your time and effort. Keep spreading the knowledge.
This is best youtube channel to learn python!!
you are the best when teaching python. period.
Thanks!
Thank you so much Corey. You are the best teacher I have ever seen.
my teachers can learn a lot from you
You always hit the depth level I need on specifics.
Thank you! You made the video interesting whilst keeping it simple, I am a beginner and this has helped a lot.
It's 8 years ago video but it is also the best video, wow
Corey, I am discovering me a fan of your great channel!! Thanks a lot, man
I've just come across this and you are about to become my saviour because I'm about 10 hours behind on my controlled assessment and have no idea what I'm doing
my brain has exploded
:o
No questions, just infinite thanks. Subscribed and recommended.
I agree with Airth. Your python series is awesome. Your videos are great. I think its the depth you go into, the many different ways to do it, and the way you should do it. Oh and so much "energy" and "flow" in the videos.
this is the content i have been searching for a month now. damn
Very simple to understand and just filtering out the important bits alone! If you do have a dedicated tutorial in udemey, I would love to subscribe!
Keep creating Sir Corey! :P :D
@Corey Schafer
1_ Thank you for this manual.
2_ Don't forget to add that a common error may occur when you give the file name with the directory, basically its when Python will interpret the directory address as string, which will cause a problem with escape characters
*Summary of the Video:*
*file.open("path", "mode")* --> opens the file in respective mode.
*Modes*
*'r'* --> for read file contents.
*'w'* --> for writing to file.
*'a'* --> for eppending file contents.
*'r+'* --> for reading and writing
*'b'* --> to open file in binary mode (for reading images)
*Note:* We can use different modes together like 'rb' can be used for reading a binary file.
*file.close()* --> closes a file.
*file.mode* --> returns the mode the file was opened in.
*file.name* --> returns the name of the file as a string.
For effiency we use context managers. The automatically close the file once we are out of the context manager the file was opened in. We can open a file using a context manager and assign the result to a variable. We can use this variable inside the context manager.
*Reading from files*
*file.read([size])* --> This method typically reads the entire content of the file. But if provided with a size (which is an optional argument), it can read 'size' number of characters. If used repeatedly, it always continues from the next character to the last character it read.
*file.readlines()* --> returns a list of all of the lines of the file. (adds
to represent start of next line)
*file.readline()* --> Reads a single line from the file. If called repeatedly, it can read all of the lines one by one.
*Note:* A file is treated as an iterable in python. This simply means that we can iterate over the lines of the file using a for loop (like we would loop over the elements of a list).
We can also use a while loop to iterate over the contents of a file. We do this by specifing the number of characters we want to read at each iteration. Then we repeatedly used file.read() method to read the characters until there is nothing left to read.
_size = 10_
_fileContents = file.read(size)_
_while len(fileContents) > 0:_ # while the length of what we have read is not 0, continue reading
_print(fileContents, end=''')_
_fileContents = file.read(size)_
The *tell()* and *seek()* methods.
Just like arrays, files are also zero-indexed. This means that the first element has a index of 0, second element has an index of 1 and so on.
Python uses a pointer to keep track of where it should be reading from and writing to the files.
In the start this point is at 0. As we read from the file, this pointer moves. For example, if we read 10 characters, this means that the pointer is not at index 10; it is going to read the 11th character next. It read from the 1st till the 10th characters (10th inclusive). Similiar mechanism is used for writing to files.
*file.tell()* --> returns the position of where the pointer is.
*file.seek(new_position)* --> sets the pointer to the specified position.
*Writing to Files*
The file should be opened in the 'write' mode. (mode = 'w').
*file.write(content)* --> writes the contents to the file.
*Note:* trying to write to a file that does not exist will first create the file and then perform the writing operation.
You can use nested (one in another) context managers to simultaneously read from a file and write to another file.
Here is the code:
_with open("readFilePath", 'r') as readFile:_
_with open("writeFilePath", 'w') as writeFile:_
_for line in readFile:
_writeFile.write(line)
You can also do:
_with open("readFilePath", 'r') as readFile:_
_with open("writeFilePath", 'w') as writeFile:_
_writeFile.write(readFile.read())_
I hope this helps!
cool
Hey man you made school much quicker and easier for me, thank you!
Thank you very much sir for putting so much effort in helping other by sharing your knowledge.
Corey, I was switching languages from R to Python and this is the best videos I could find. Kudos and keep up the great work !!
Love your Python (and other) videos - some of the best coding tutorials on TH-cam. Very clear, detailed, in-depth explanations that get right to the point. Great work!
Ideas for future tutorials:
-Much more on classes, including composition, polymorphism, when to use classes vs other data structures, etc.
-Enums and when to use them (introduced recently in Python)
-Examples of when to choose different data structures and how to implement each.
- Oauth and working with APIs through Python
-PDB / debugging
-Testing web apps
-Selenium and Python
-Beautiful Soup
-Pytest
-Pylint
-TDD
-Encapsulation / structuring code in python effectively
-Advanced namespaces / modules / packages
-Flask (advanced or in-depth, eg explaining the app context and how working with Flask blueprints is different from the usual modules and if ‘__name__’ == ‘__main__’
- Intermediate/ Advanced object oriented programming
- Refactoring and code smells
- Functional programming
- Advanced Sublime Text
- Workflow, eg syncing dev environments across different platforms, version control for dotfiles, etc.
- Productivity tips
- Design patterns
- Medium/low-level networking and web programming with Python (understanding HTML headers, session objects / cookies, HTTP protocol, servers, AJAX and REST APIs, etc.
- Setting up a personal web server, mail server, file server, owncloud, etc.
- Executing JavaScript with Python
- Setting up a LAN / basic home networking
- Scripting and automation tips/ideas/anything
- MongoAlchemy and/or Pymongo and/or SQLAlchemy
- Building a web app with Python/Flask backend and JavaScript/Angular frontend
- Advanced regular expressions (maybe covered in your newest video)-e.g., escaping regex strings
- String templating, text replacement, etc.
- Collections module
- Modules that are useful or should be in the standard library but are not
- Advanced / in-depth primitive operations, e.g. string and dict methods.
Thank you!
the best python teacher ever
finally someone that explains it properly! Thank you :)
I admit, your style of presentation is as good as your knowledge base. Love from New Delhi !
This is so fkng good, tkx for the content, srly, well explained and covers a lot of ground, loved it.
I’ve been getting better at Python thanks to your videos
This man deserves Computer Science professor of MIT
Thanks for explaining everything in such a simple manner
16:10 Careful! File contents(if exists) are erased the moment it's opened in write mode.
U r experienced
too late, deleted my bank account passwords
respected sir you are a legend one of the finest tutorial til date i wish i had a teacher like you to guide me on coding thank you sir for your help
You're a blessing, thank you
I'm learning so much from you tutorials without getting frustrated ,thank you so much !
How do I write and read a file simultaneously .I tried to do but after every read operation its simultaneously writing the same content the no of times i run the prog which is not what i want .Please help !! Thank you !
Well. Hope this isn't too late 😅
But you need to control the file pointer on the open file object, when you open a file in r+ or w+ mode the file pointer starts from the top of the file (0) so you'll need to get it to the end of the file before writing new data
Your video made EVERYTHING CLEAR for me!!!!!!!!
How would I read/print a random line from the file
Use f.readline() in a loop (or for line in f: ) to make a list of all the lines and then use random.choice() to select a random element of that list
These tutorials are the most bestest.
for line in f:
how does it take in one line like we havent specified anything
line why doesnt line iterate through each character .
how does it iterate through each line
can someone please help me? :)
yes same doubt buddy!!!!!
@@vaibhavdumaga7229 Same issue here. But I think it is in-built and so the for-loop function automatically knows. From documentation, it says that some file objects are iterable, meaning when used in a loop, it automatically "knows" how to go to the next item in the file object.Don't fully understand, but it seems to be in built so it's automatic. See for yourself here under iterable: docs.python.org/3/glossary.html#term-iterable
This helped a lot actually, thanks.
I started learning Python a few days ago, and decided to create a game (never done coding before). I was having an issue with trying to figure out how to define a variable to a specific line (readline; didn't know that at the time), as a means of tracking the progress and associated flags as the player goes through the game. (An RPG; so far working systems, not all fully integrated: Main Menu, Combat Module, Character Class + Character Power Choosers, and Class for Enemies and scaling stats based on level)
If any of you were wondering how to do that, or needed reinforcement for it:
I created (using another, not shown, while loop + function), gameSave.txt file, and defined values to put into it (writing it into existence)
And for loading I use the below to pull the values from that written file, and save them as variables as it runs
############# DELETE THE # IF YOU ARE TRYING TO RUN THIS IN A FILE, AND MAKE SURE TO CREATE A FILE CALLED gameSave.txt and put stuff on first 3 lines#######
#################DELETE EVERYTHING TO THE RIGHT OF A # THAT IS MY ANNOTATION EXPLAINING IT
global pclevel #define the variables as with the global tag, this helps avoid issues where you can't set a value to a variable while it is within a function (might not be needed in some cases)
global pcxp
global pcname
pclevel = '' #this is empty in the middle, two ' ergo empty variable
pcxp = ''
pcname = ''
with open('gameSave.txt', 'r') as g:
#defined g as the term to open the file, as it is shorter and I'm feeling lazy after awhile
gsave = g
#gsave = g, I didn't use gsave here but figured it is best to store the values as it is a small file, would probably not recommend unless you intend to use it later
pclevel = g.readline()
#I stored the values in lines 1-3, and so set a value to each based on sequential readline, which is read as g (where we defined open('gameSave.txt', 'r')).readline()
pcxp = g.readline()
#gets the second line
pcname = g.readline() #gets the third line
print(pclevel)
print(pcxp)
print(pcname)
#the above 'open' redefines the variables to the values that are stored within each line of the file, in sequential order, and then printing that variable will print out the stored information
#worth noting, if you wanted to do say print('My name is ' + pcname + ' and my level is ' + pclevel)
#you would need to do a str(pclevel) for example, to convert the stored number into a string; attempting to print an integer + a str won't work
#i.e. print('My name is ' + str(pcname) + ' and my level is ' + str(pclevel)) #never hurts to be safe, the name SHOULD be stored as a str, but idk maybe you're R2D2 or something
*** Thanx Corey - Excellent Video. Nicely spoken, great pace, very informative and easily understandable.
Great work - thank you! :¬)
Absolute killer tutorial! Thank you! I've subscribed. I'm in Lambda School learning python and this cleared up a lot. I appreciate it.
Great tuts. I assume this is for python 3? I tried to do this in 2.7 and it doesn't seem to like the syntax with the "end". I guess I should start transition to 3. Overall like your style of teaching.
Edit- I got it to work if in python 2.7, you have do an import -> from __future__ import print_function
Sorry for the late reply. Yes, this is Python 3. It took me a long time to transition over too, but since it is the recommended version now it is a good idea to switch over if possible.
The same thing happened to me lmao. I checked my version and it is 3.6. Now im totally lost. I can use it in IDLE but it failed in Sublime
Wow. This channel is going to be an epic for Python learning. Every topic covers the crux of the items cleverly
PLEASE POST SOME TUTORIAL ON NETWORK PROGRAMMING USING PYTHON....THANKS IN ADVANCE !!
ARe you an ethical hacker?
Udemy has just the right one for you "ON NETWORK PROGRAMMING USING PYTHON." they are very affordable too.
th-cam.com/video/Lbfe3-v7yE0/w-d-xo.html
This is a great tutorial, You simplify complex topics and make it simple to understand
awesome tutorial :)
+Pravesh Jangra Thanks! Glad you enjoyed it.
Amazing.. am loving Python even more now ! Please dd more tutorials to Files on files like reading from IO, memory, csv files, or extracting data from unstructured format .
"...it didn't delete the rest of the content" HAHA
man thanks for all these videos you are really a king
Thx for vids signed up to became your patron!
BTW, what about that tmp files and in memory files vid, is it on your channel?
Thanks, Alex! I really appreciate that. I haven't recorded the tmp and in-memory files video yet, but I still plan on putting one together in the near future after I get some other videos in my list finished up and published.
Thanks again!
Looking forward :)
This is pure gold!!! Added to bookmarks!
OMG THS IS M FAVURIT VEDIO EVVRR
sorry jude thats wrong
same
Finally! A worthy tutorial!
More videos please!!
The most useful python series on the net. thanks alot
Yo.... this is much simpler in python than in java
This man who made this video helped me a lot, l cannot describe with words anyways. many thanks
Who's here from UoPeople?
Thankyou I am able to Tweek this into my file today as an option for the user to read rules and save their text to be used later. Thumbs up :)
Thumbs up for puppy pic
I finally found someone who makes sense. Corey, this is amazing thank you!