I'm trying to create a text file that is named using a variable in my program. Only problem is, I can't specify a directory when i'm naming it using a variable. (vac_postcode is the variable i'm using to name the file)
centrebypostcode = open(C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode + ".txt"', "a+")
centrebypostcode.write("\n")
centrebypostcode.write(vac_center)
centrebypostcode.close()
I'm using "a+" because I need the program to create the text file if it doesn't exist, but if it does, it just appends what I need it to, to the text file. (This is my understanding of the usage of "a+")
open(r'C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode + ".txt"', "a+" ') does not work either, unfortunately.
You have to keep the variable name outside the quoted string, change the line to
centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre" + "\\" + vac_postcode + ".txt", "a+")
Edited: the raw string literal cannot have the last backslash, so you need to concatenate that separately.
It looks like that quotation is wrong.
try with this
centrebypostcode = open(r"C:\Users\Rich\Desktop\Assignment\Centre\{}.txt".format(vac_postcode), "a+")
I just try to be more descriptive
filenames = ["my_file1","my_file2"]
for filename in filenames:
filename = f"C:\Users\Rich\Desktop\Assignment\Centre\vac_postcode\{filename}.txt"
with open(filename, "a+") as fh:
fh.write("Hello world")
Related
I posted a question yesterday in similar regards to this but didn't quite gauge the response I wanted because I wasn't specific enough. Basically the function takes a .txt file as the argument and returns a string with all \n characters replaced with an '_' on the same line. I want to do this without using WITH. I thought I did this correctly but when I run it and check the file, nothing has changed. Any pointers?
This is what I did:
def one_line(filename):
wordfile = open(filename)
text_str = wordfile.read().replace("\n", "_")
wordfile.close()
return text_str
one_line("words.txt")
but to no avail. I open the text file and it remains the same.
The contents of the textfile are:
I like to eat
pancakes every day
and the output that's supposed to be shown is:
>>> one_line("words.txt")
’I like to eat_pancakes every day_’
The fileinput module in the Python standard library allows you to do this in one fell swoop.
import fileinput
for line in fileinput.input(filename, inplace=True):
line = line.replace('\n', '_')
print(line, end='')
The requirement to avoid a with statement is trivial but rather pointless. Anything which looks like
with open(filename) as handle:
stuff
can simply be rewritten as
try:
handle = open(filename)
stuff
finally:
handle.close()
If you take out the try/finally you have a bug which leaves handle open if an error happens. The purpose of the with context manager for open() is to simplify this common use case.
You are missing some steps. After you obtain the updated string, you need to write it back to the file, example below without using with
def one_line(filename):
wordfile = open(filename)
text_str = wordfile.read().replace("\n", "_")
wordfile.close()
return text_str
def write_line(s):
# Open the file in write mode
wordfile = open("words.txt", 'w')
# Write the updated string to the file
wordfile.write(s)
# Close the file
wordfile.close()
s = one_line("words.txt")
write_line(s)
Or using with
with open("file.txt",'w') as wordfile:
#Write the updated string to the file
wordfile.write(s)
with pathlib you could achieve what you want this way:
from pathlib import Path
path = Path(filename)
contents = path.read_text()
contents = contents.replace("\n", "_")
path.write_text(contents)
I have some text file with these lines:
Zip=false
Run=false
Copy=true
FileName=c:\test\test.doc
Now I need to load this text file, change some values and write back to same text file.
So I load it to a dictionary, change values on the dictionary and write back.
The problem is that that backslashes in the FileName path are being duplicate and in the new file I get FileName=c:\test\test.doc.
Here is the dictionary creation:
def create_dictionary(filename):
try:
file = open(filename, 'r')
except:
print("Error " + filename + " not found or path is incorrect")
else:
contents = file.read().splitlines()
properties_dict = {}
for line in contents:
if not line.startswith("#") and line.strip():
# print (line)
x, y = line.split("=")
properties_dict[x] = [y]
return properties_dict
Here is writing back to the file
# Update the properties file with updated dictionary
fo = open(properties_file, "w")
for k, v in dic.items():
print(str(k), str(v))
fo.write(str(k) + '=' + str(v).strip("[]'") + '\n')
fo.close()
This seems to be working:
def create_dictionary(file_name):
try:
properties_dict = {}
with open(file_name, "r") as file:
contents = file.read().splitlines()
for line in contents:
if not line.startswith("#") and line.strip():
property_name, property_value = line.split("=")
properties_dict[property_name] = property_value
return properties_dict
except FileNotFoundError:
print(f"Error {file_name} not found or path is incorrect")
def dict_to_file(properties_dict, file_name):
try:
file_dirname = os.path.dirname(file_name)
if not os.path.exists(file_dirname):
os.makedirs(file_dirname)
except FileNotFoundError: # in case the file is in the same directory and "./" was not added to the path
pass
with open(file_name, "w") as file:
for property_name, property_value in properties_dict.items():
file.write(f"{property_name}={property_value}\n")
properties_dict = create_dictionary("./asd.txt")
dict_to_file(properties_dict, "./bsd.txt")
Since, there was a request for more explanations, I am editing this post.
Actually the critical part is not file.write(f"...") as #pktl2k pointed out. The critical part is changing properties_dict[x] = [y] to properties_dict[x] = y.
In Python strings, when you want to escape special characters you use a backslash ( \ ). The FileName parameter in your file has one of those special characters which is also a backslash (FileName=c:\test\test.doc). Thus, when you read this file, Python stores it as string as:
"c:\\test\\test.doc"
Which is totally normal. And when you want to write this string back to a file, you will get your desired output ( no double backslashes ). However, in your code, you do not have this value as a string. You have it as a list that is holding this value as string. When you call str built-in function on a list (which by the way is a built-in class), list class' __repr__ function is called (actually __str__ is called but in list __str__ calls __repr__ as far as I know, but let's not go so much into details of these functions. See this link if you want to learn more about it) to get a string representation of your list. In this process, all your list is converted to a string with all of its elements as it is. Then you get rid of some characters in this string representation using strip("[]'"), this is the actual cause of your problem.
Now, why did I write everything from the beginning and not only the part that is important as #pktl2k kindly asked. The reason is because if you noticed in create_dictionary function the author forgot to close the file using file.close(). This is a common problem and that's why there is a syntax like with open(....). I wanted to emphasis that: it is better to use with open(...) syntax whenever we would like to manipulate contents of a file. I could also write this as a small note as well, but I think it is better with this way (so it is a personal preference).
I have a folder with csv formated documents with a .arw extension. Files are named as 1.arw, 2.arw, 3.arw ... etc.
I would like to write a code that reads all the files, checks and replaces the forwardslash / with a dash -. And finally creates new files with the replaced character.
The code I wrote as follows:
for i in range(1,6):
my_file=open("/path/"+str(i)+".arw", "r+")
str=my_file.read()
if "/" not in str:
print("There is no forwardslash")
else:
str_new = str.replace("/","-")
print(str_new)
f = open("/path/new"+str(i)+".arw", "w")
f.write(str_new)
my_file.close()
But I get an error saying:
'str' object is not callable.
How can I make it work for all the files in a folder? Apparently my for loop does not work.
The actual error is that you are replacing the built-in str with your own variable with the same name, then try to use the built-in str() after that.
Simply renaming the variable fixes the immediate problem, but you really want to refactor the code to avoid reading the entire file into memory.
import logging
import os
for i in range(1,6):
seen_slash = False
input_filename = "/path/"+str(i)+".arw"
output_filename = "/path/new"+str(i)+".arw"
with open(input_filename, "r+") as input, open(output_filename, "w") as output:
for line in input:
if not seen_slash and "/" in line:
seen_slash = True
line_new = line.replace("/","-")
print(line_new.rstrip('\n')) # don't duplicate newline
output.write(line_new)
if not seen_slash:
logging.warn("{0}: No slash found".format(input_filename))
os.unlink(output_filename)
Using logging instead of print for error messages helps because you keep standard output (the print output) separate from the diagnostics (the logging output). Notice also how the diagnostic message includes the name of the file we found the problem in.
Going back and deleting the output filename when you have examined the entire input file and not found any slashes is a mild wart, but should typically be more efficient.
This is how I would do it:
for i in range(1,6):
with open((str(i)+'.arw'), 'r') as f:
data = f.readlines()
for element in data:
element.replace('/', '-')
f.close()
with open((str(i)+'.arw'), 'w') as f:
for element in data:
f.write(element)
f.close()
this is assuming from your post that you know that you have 6 files
if you don't know how many files you have you can use the OS module to find the files in the directory.
I'm fairly new to python and I'm having an issue with my python script (split_fasta.py). Here is an example of my issue:
list = ["1.fasta", "2.fasta", "3.fasta"]
for file in list:
contents = open(file, "r")
for line in contents:
if line[0] == ">":
new_file = open(file + "_chromosome.fasta", "w")
new_file.write(line)
I've left the bottom part of the program out because it's not needed. My issue is that when I run this program in the same direcoty as my fasta123 files, it works great:
python split_fasta.py *.fasta
But if I'm in a different directory and I want the program to output the new files (eg. 1.fasta_chromsome.fasta) to my current directory...it doesn't:
python /home/bin/split_fasta.py /home/data/*.fasta
This still creates the new files in the same directory as the fasta files. The issue here I'm sure is with this line:
new_file = open(file + "_chromosome.fasta", "w")
Because if I change it to this:
new_file = open("seq" + "_chromosome.fasta", "w")
It creates an output file in my current directory.
I hope this makes sense to some of you and that I can get some suggestions.
You are giving the full path of the old file, plus a new name. So basically, if file == /home/data/something.fasta, the output file will be file + "_chromosome.fasta" which is /home/data/something.fasta_chromosome.fasta
If you use os.path.basename on file, you will get the name of the file (i.e. in my example, something.fasta)
From #Adam Smith
You can use os.path.splitext to get rid of the .fasta
basename, _ = os.path.splitext(os.path.basename(file))
Getting back to the code example, I saw many things not recommended in Python. I'll go in details.
Avoid shadowing builtin names, such as list, str, int... It is not explicit and can lead to potential issues later.
When opening a file for reading or writing, you should use the with syntax. This is highly recommended since it takes care to close the file.
with open(filename, "r") as f:
data = f.read()
with open(new_filename, "w") as f:
f.write(data)
If you have an empty line in your file, line[0] == ... will result in a IndexError exception. Use line.startswith(...) instead.
Final code :
files = ["1.fasta", "2.fasta", "3.fasta"]
for file in files:
with open(file, "r") as input:
for line in input:
if line.startswith(">"):
new_name = os.path.splitext(os.path.basename(file)) + "_chromosome.fasta"
with open(new_name, "w") as output:
output.write(line)
Often, people come at me and say "that's hugly". Not really :). The levels of indentation makes clear what is which context.
I my python GUI, I have created a questionaire. In this it allows me to ask questions and then save them to a text file. i have saved them to a text file using a variable, so each file is different. E.G.
name = james (the file will be called james)
or...
name = Charlie (the file will be called Charlie)
I am able to write and save to the text file. What I need to b able to do is find a way to open the text file by using a variable. this will allow me to input a name, such as "James" and I can open the file called James.
This is the code I have at the moment.
name = entry.get()
# this collects the name from an entry box.
newfile = (name.txt,"r")
# name is the variable I am using.
loaded = (newfile.read())
# this would hopefully put the file text into a variable
textbox.delete(0.0, END)
# this will clear the text box
textbox.insert(END, loaded)
# this put the text from the file (in loaded) into the text box
Is there a way to allow me to do this? I hope this makes sense. Thank you all who help.
First, you're not calling open anywhere. Just writing, e.g., (path, "r") doesn't give you a file object, it just gives you a tuple of two strings.
Second, literal strings have to be in quotes. And if you want to concatenate two strings, it doesn't matter whether they're in variables or literals, that's just +.
So:
newpath = name + ".txt"
newfile = open(newpath, "r")
Also, while you're at it, you should close the file somewhere. Ideally by using a with statement:
newpath = name + ".txt"
with open(newpath, "r") as newfile:
loaded = newfile.read()