I'm pretty new to programming and I'm currently learning about the open() function used in python. My current goal is to create a to-do list, my first task was to create a filename in read mode otherwise if the file doesn't exist it is to be created in read/write mode "w+".
My current issue is the open() function isn't creating that empty "list.txt" which is the same folder where my code is saved into. I appreciate any feedback :)
def get_list(filename):
try:
f = open(filename, 'r') # try to open the file in read mode
except: # if the file doesn't exist...
f = open(filename, 'w+') # create it by opening it in write
data = f.readlines() # read the content of the file into a list
f.close() # close the file
return data # return data
You're almost there. You have to call the function you created with the Path where you would like the .txt file. The path is the location from the drive where it is stored. The following code is an example of what it should look like.
get_list('C:\Users\jsmith\list.txt')
Related
Good morning. I am trying to create a "for" loop to search for every file with .txt in a single folder and encrypt them. I was able to successfully do it with a single file but I have been tasked to create a loop to repetitively encrypt multiple files in a single folder
single_encrypt_file.py
from cryptography.fernet import Fernet
file = open('key.key', 'rb')
key = file.read()
file.close()
for filename in os.listdir('testfolder'):
with open(filename, 'rb') as f:
data = f.read()
fernet = Fernet(key)
encrypted = fernet.encrypt(data)
with open(filename, 'wb') as f:
f.write(encrypted)
I am still a beginner in python and programming so it would be great if anyone have ideas on how I should modify my current code. Cheers!
Update: I have modified the code based on the given answer but I am getting an error saying "No such file or directory: testfile.txt" when the file clearly exists when I went to check.
First thing is to do is to find all the file names in the folder. To do that use os.listdir().
Then you simply loop through the filenames:
import os
for filename in os.listdir('dirname'):
##do what you want
Be careful because you might want to check if the folder contains only the files you want to encrypt. Otherwise create an exception to ignore unwanted files
I managed to figure out the problem. turns out os.listdir() method gives you filenames without paths only and as I needed to open files in my current directory (testfolder) I needed to use another which is os.path.join().
single_encrypt_file.py
for filename in os.listdir('testfolder'):
testpath = os.path.join('testfolder', filename)
#run encryption codes
I am able to write to a text file using .write(). But after I close() the file and open it again all the written data is gone...? Is there any way that I can permanently save this data on the file?
def writeToFile():
myFile = open("myText.txt","w")
for each in range(8,10):
record = "This is record number {} in the file\n".format(each)
myFile.write(record)
myFile.close()
writeToFile()
So what i meant was that the first time i run this program it appends to the file. After this when i close the program and run it again i want it to write to the file again, but instead it only overrides it, i.e the earlier data is deleted each time i close the program.
The data you wanted to write was indeed permanently written... until you opened again overwriting the previous data.
You have different modes to open the file.
If you know that the file has important data and only want to read it, use this mode.
file = open('./path_to_file', 'r')
If you want to overwrite the data, use this one instead:
file = open('./path_to_file', 'w')
Optionally, you can use this other way instead, and it will close the file for you.
with open('./path_to_file', 'r') as read_file:
for line in read_file:
print line
This will open the file, read it line by line writing it on the screen and closing it for you at the end.
Finally, if you need to open it again and append new content at the end of the file, just use this:
file = open('./path_to_file', 'a')
I'm trying my hand at this rosalind problem and am running into an issue. I believe everything in my code is correct but it obviously isn't as it's not running as intended. i want to delete the contents of the file and then write some text to that file. The program writes the text that I want it to, but it doesn't first delete the initial contents.
def ini5(file):
raw = open(file, "r+")
raw2 = (raw.read()).split("\n")
clean = raw2[1::2]
raw.truncate()
for line in clean:
raw.write(line)
print(line)
I've seen:
How to delete the contents of a file before writing into it in a python script?
But my problem still persists. What am I doing wrong?
truncate() truncates at the current position. Per its documentation, emphasis added:
Resize the stream to the given size in bytes (or the current position if size is not specified).
After a read(), the current position is the end of the file. If you want to truncate and rewrite with that same file handle, you need to perform a seek(0) to move back to the beginning.
Thus:
raw = open(file, "r+")
contents = raw.read().split("\n")
raw.seek(0) # <- This is the missing piece
raw.truncate()
raw.write('New contents\n')
(You could also have passed raw.truncate(0), but this would have left the pointer -- and thus the location for future writes -- at a position other than the start of the file, making your file sparse when you started writing to it at that position).
If you want to completley overwrite the old data in the file, you should use another mode to open the file.
It should be:
raw = open(file, "w") # or "wb"
To resolve your problem, First read the file's contents:
with open(file, "r") as f: # or "rb"
file_data = f.read()
# And then:
raw = open(file, "w")
And then open it using the write mode.This way, you will not append your text to the file, you'll just write only your data to it.
Read about mode files here.
I'm writing a simple parser. For now, it reads the whole current dir and open files with 'r' and 'w' permissions for all files that end with ".w". Here's the code for it:
import os
wc_dir = os.path.dirname(os.path.abspath(__file__))
files = [f for f in os.listdir(wc_dir) if os.path.isfile(os.path.join(wc_dir,f))]
comp_files_r = [open(f, 'r') for f in files if f.endswith(".w")]
comp_files_w = [open(f, 'w') for f in files if f.endswith(".w")]
As you can see, I have two lists with "open objects" with read and write permissions for all files in the current folder that end with ".w". For now, I have just one file. So, consider the following:
print comp_files_r
print comp_files_w
Output:
[<open file 'app.w', mode 'r' at 0x7effd48274b0>]
[<open file 'app.w', mode 'w' at 0x7effd4827540>]
It happens that, when I try to read the 'app.w' file:
def parse():
for f in comp_files_r:
with f as file:
data = file.read()
print repr(data)
parse()
I get an astonishing empty string for no reason. I've managed to discover that, all that I save in 'app.w' gets erased when I execute the code with the "w list comprehension". So why is that? I've learned from pain that trying to both read and write a file in "r+" mode can lead to weird results. That's not the situation. I've created different objects from the same file, and this is messing with the content of the file itself. Why?
It looks to me that your issue is that you're opening the file in 'w' mode. When you open a file in 'w' mode, the current file is deleted and replaced with the new file. 'r+' mode is for reading and editing.
I'd be willing to bet that if you read the contents of the files between the lines where you open them for reading and and the line where you open them for writing, you will see the contents of the files as you expect them to be.
how can I clear a complete csv file with python. Most forum entries that cover the issue of deleting row/columns basically say, write the stuff you want to keep into a new file. I need to completely clear a file - how can I do that?
Basically you want to truncate the file, this can be any file. In this case it's a csv file so:
filename = "filewithcontents.csv"
# opening the file with w+ mode truncates the file
f = open(filename, "w+")
f.close()
Your question is rather strange, but I'll interpret it literally. Clearing a file is not the same as deleting it.
You want to open a file object to the CSV file, and then truncate the file, bringing it to zero length.
f = open("filename.csv", "w")
f.truncate()
f.close()
If you want to delete it instead, that's just a os filesystem call:
import os
os.remove("filename.csv")
The Python csv module is only for reading and writing whole CSV files but not for manipulating them. If you need to filter data from file then you have to read it, create a new csv file and write the filtered rows back to new file.