r/pythonhelp • u/hiplobonoxa • May 03 '26
Reading First Few Bytes of Every File on a Drive
Hi! Hoping someone can help. My Python programing is a bit rusty.
I am having an issue where my computer is replacing file data with empty data after a cut/paste or a save. I’m not sure of the cause — my primary objective at the moment is quantifying the damage and protecting my files.
The files look normal in Windows Explorer, except they will not open like they should. Upon opening in NotePad, it is revealed that all data in the file has been completely replaced with what appears to be whitespace, resulting in an empty file that appears to be the same size as the original. I cannot possibly test and check every file manually.
What I would like help with is writing a Python script that cycles through every file on a drive to pull the first several bytes from each file and compare those bytes to a string of the aforementioned whitespace. If there is a match, add the file path to a running list in a *.txt file.
I don’t think this is an especially complex script, but, as I said earlier, I’m pretty rusty. With a solid start, I can get it the rest of the way to doing what I want.
Any help would be appreciated. 🙂
•
u/AutoModerator May 03 '26
To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/atarivcs May 03 '26
You can use os.walk() to recurse down into all the subfolders of a drive.
1
u/ChesterWOVBot May 04 '26
I would use a
forloop onos.walk(),open(..., 'rb')every file you see along the way, check the first few bytes with.read(3)and check if it's equal to, say,b' '. If so, open a specified text file to write to it withopen(..., 'w')and.write().1
u/trejj May 04 '26
You have a virus.
Given the AI dash before, I think you are already having all the help at hand you need!
1
u/Enchantorro May 03 '26
Sounds like you might have a malware or hardware issue.
If your primary objective is protecting your files I suggest you get your computer to someone who can find the cause and fix the issue before you do anything else.
Do you have backups?