class NewTab():
def __init__(self, song_title, artist_name):
self.song_title = song_title
self.artist_name = artist_name
name1 = self.artist_name + "_" + self.song_title
name2 = name1.replace(" ", "")
new_file = open("~/Documents/"+name2+".txt", "a+")
tab = NewTab(raw_input("Song Title: "), raw_input("Artist Name: "))
I am trying to create a new file (assuming it doesn't already exist) whose name is generated from two strings of User input. For example:
"Song Title: " >> Personal Jesus
"Artist Name: " >> Depeche Mode
should result in creating: ~/Documents/DepecheMode_PersonalJesus.txt
Unfortunately I am always left with:
IOError: [Errno 2] No such file or director: '~/Documents/DepecheMode_PersonalJesus.txt'
I have tried different open() modes, such as "w", "w+" and "r+" to no avail.
I have also tried placing name1, name2, and new_file into a method outside of __init__ like so:
def create_new(self):
name1 = self.artist_name + "_" + self.song_title
name2 = name1.replace(" ", "")
new_file = open("~/Documents/"+name2+".txt", "a+")
tab.create_new()
but this results in the exact same Error.
I have set my /Documents folder Permissions (Owner, Group, Others) to Create and delete files.
Beyond that, I am at a complete loss as to why I cannot create this file. It is clearly structuring the file name and directory the way that I want it, so why won't it go ahead and create the file?
Use os.path.expanduser() function to get a full valid path with "~" resolved and pass this to open()
new_file = open(os.path.expanduser("~/Documents/")+name2+".txt", "a+")
this will resolve "~" to something like /home/user and join it with the rest of the path elements.
If you don't necessarily need to use "a+" then having "wb" as a second parameter will automatically open a file.
foo = open("bar", "wb")
Related
Good day everyone, How can i make this thing make TRUE? I already have existed .txt files but the outcome always False.
ID = input("Enter the name of your .txt file: ") +".txt" +"'"
IDS = "'" + ID
file_exists = os.path.exists(IDS)
print(file_exists)
print(IDS)
Get rid of ' before and after the file name:
ID = input("Enter the name of your .txt file: ") +".txt"
file_exists = os.path.exists(ID)
print(file_exists)
print(ID)
For example, if you had foo.txt and you put foo into your program, then your current code would look for a file named 'foo.txt', not foo.txt.
Try this:
#You may want to use str.strip() to get rid of unnecessary whitespaces
ID = input("Enter the name of your .txt file: ").strip() + ".txt"
file_exists = os.path.exists(ID)
print(f'{ID} exists') if file_exists else print(f'{ID} file does not exist')
Remove the quotes, you are adding single quotes to start and end of your string. Your code should look like this:
ID = input("Enter the name of your .txt file: ") +".txt"
file_exists = os.path.exists(ID)
print(file_exists)
print(IDS)
Quotes in programming languages indicate what are strings, and they are omitted by the interpreter when you output it into a terminal (print)
write a python program to create a .html file in a directory, the directory can be created correctly, use function open to create this .html file and try to write some content in this file,but the .html file can not be created,
def save_public_figure_page(self,type,p_f_name):
glovar.date = time.strftime("%Y%m%d", time.localtime())
p_f_page_file_directory = os.path.join("dataset", "html",type,glovar.date,p_f_name)
data_storage.directory_create(p_f_page_file_directory)
html_user_page = glovar.webdriver_browser.page_source
p_f_page_file = os.path.join(p_f_page_file_directory,type + "_" + p_f_name + ".html")
html_file = open(p_f_page_file, "w", encoding='utf-8')
html_file.write(html_user_page)
html_file.close()
the directory_create function in data_storage is:
#create the file storage directory
def directory_create(path):
directory = os.path.join(os.path.dirname(__file__),path)
if not os.path.exists(directory):
os.makedirs(directory)
it errors:
<class 'FileNotFoundError'> at /public_figure_name_sub
[Errno 2] No such file or directory: 'dataset\\html\\public_figure\\20170404\\Donald Trump \\public_figure_Donald Trump .html'
the current directory is under /dataset/, I found the directory:
F:\MyDocument\F\My Document\Training\Python\PyCharmProject\FaceBookCrawl\dataset\html\public_figure\20170404\Donald Trump
has been created correctly,but the file——public_figure_Donald Trump .html can not be created correctly,could you please tell me the reason and how to correct
As suggested by Jean-François Fabre, your file has a space just before the ".html".
To solve this, use trim() in the variable p_f_name in your 7th line:
# Added trim() to p_f_name
p_f_page_file = os.path.join(p_f_page_file_directory,type +
"_" + p_f_name.trim() + ".html")
This will create the file:
public_figure_Donald Trump.html
instead of
public_figure_Donald Trump .html
PD: Anyway your filename has a lot of spaces between Donald and Trump. I don't know where the file name comes but you might want to fix it.
Function save_public_figure_page
class public_figure:
def save_public_figure_page(self, type, p_f_name):
glovar.date = time.strftime("%Y%m%d", time.localtime())
p_f_name = p_f_name.trim() # Trim the name to get rid of extra spaces
p_f_page_name = '{t}_{pfn}.html'.format(t=type, pfn=p_f_name)
p_f_page_file_directory = os.path.join(
directory, # Add the directory from the data_storage.directory property
"dataset", "html",
type, glovar.date, p_f_name,
)
if data_storage.directory_create(self.p_f_page_file_directory):
html_user_page = glovar.webdriver_browser.page_source
p_f_page_file = os.path.join(p_f_page_file_directory, p_f_page_name)
html_file = open(p_f_page_file, "w", encoding='utf-8')
html_file.write(html_user_page)
html_file.close()
directory_create method of data_storage
#create the file storage directory
class data_storage:
def directory_create(self, path):
self.directory = os.path.join(os.path.dirname(__file__), path)
if not os.path.exists(self.directory):
try:
os.makedirs(self.directory)
except:
raise
else:
return True
else:
return True
Okay, so here's the deal, folks:
I've been experimenting with Python(3.3), trying to create a python program capable of generating random names for weapons in a game and replacing their old names, which are located inside a text file. Here's my function:
def ModifyFile(shareddottxt):
global name
a = open(str(shareddottxt) , 'r')
b = a.read()
namefix1 = '''SWEP.PrintName = "'''
namefix2 = '''" //sgaardname'''
name1 = b.find(namefix1) + len(namefix1)
name2 = b.find(namefix2, name1)
name = name + b[name1:name2] ## We got our weapon's name! Let's add the suffix.
c = open((shareddottxt + ".lua"), 'r+')
for line in b:
c.write(line.replace(name, (name + namesuffix)))
c.close()
a.close
As you can see, I first open my text file to find the weapon's name. After that, I try to create a new file and copy the contents from the old one, while replacing the weapon's name for (name + namesuffix). However, after calling the function, I get nothing. No file whatsoever. And even if I DO add the file to the folder manually, it does not change. At all.
Namesuffix is generated through another function early on. It is saved as a global var.
Also, my text file is huge, but the bit I'm trying to edit is:
SWEP.PrintName = "KI Stinger 9mm" //sgaardname
The expected result:
SWEP.PrintName = "KI Stinger 9mm NAMESUFFIX" //sgaardname
Where did I mess up, guys?
Something like this is more pythonic.
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r+') as file:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
file.seek(0)
file.write(new_lines)
If you don't want to replace that file
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r') as file, open(filename + ".temp", 'w') as temp:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
temp.write(new_lines)
Consider the following code:
import pickle
def open_file(fname, fname1 = None):
# returns a new OPEN file
if fname1:
while fname == fname1:
f_name = input("File already open, filename: ")
f = None
while not f:
try:
f = open(fname, "rb")
except IOError:
fname = input("File not found, filename: ")
print(fname, "open")
return f
def get_2cubes():
a_name = input("\nWhat is the name of the first cube's file? ")
a_file = open_file(a_name)
#a_cube = pickle.load(a_file)
a_file.close()
b_name = input("\nWhat is the name of the second cube's file? ")
b_file = open_file(b_name, a_name)
#b_cube = pickle.load(b_file)
b_file.close()
#return a_cube, b_cube
get_2cubes()
The code is meant to open a second file only if it's not the first file.
The first file's name is represented by fname1 in open_file(). If the name of the second file (b_name in this case) matches that of the first file the user will be prompted to enter a new name.
I supplied a default argument of None for the fname1 parameter because the function will sometimes be used only for opening one file and not for also comparing it to another file. However, I can't seem to override the default argument.
The a_name variable from the 7th line of get_2cubes is not being recognized by the if fname1: condition in open_file, and as a result I can open the same file twice. How would I correct this?
I think you need to use raw_input. Otherwise the text entered will treated as a variable name, and therefore will equal to None. (Unless you're on Python 3)
I have a library where I want to create a new book and then add it to my list of books.
What I have problems with is to save the file between calls.
This is how I read the file:
def read_bookfile():
try:
booklibrary_file = open("a.txt")
booklibrary_list = []
booklist = booklibrary_file.readlines()
for rad in booklist:
linelist = rad.split("/")
title = linelist[0]
firstname = linelist[1]
lastname = linelist[2]
isbn = int(linelist[3])
availability = linelist[4]
borrowed = linelist[5]
late = linelist[6]
returnday = linelist[7]
b = Book(title, firstname, lastname, isbn, availability, borrowed, late, returnday)
booklibrary_list.append(b)
booklibrary_file.close()
return booklibrary_list
Now I want to know how to save to my file.
In order to save to a file, you have to open it in Write-Append mode.
library_file = open("a.txt", "a")
...
library_file.write("Some string\n")
...
library_file.close()
Refer to Python's documentation on Built-in Functions for more information.
First off, here's an easier way to read, assuming those eight fields are the only ones:
def read_bookfile(filename="a.txt"):
with open(filename) as f:
return [Book(*line.split('/')) for line in f]
Now, to save:
def save_bookfile(booklist, filename='a.txt'):
with open(filename, 'w') as f:
for book in booklist:
f.write('/'.join([book.title, book.firstname, book.lastname, str(book.isbn),
book.availability, book.borrowed, book.late, book.returnday])
+ '\n')
assuming the Book model just saves those attributes in as they were passed (as strings).
Explanations:
The with statement opens your file and makes sure that it gets closed when control passes out of the statement, even if there's an exception or something like that.
Passing in the filename as an argument is preferable, because it allows you to use different filenames without changing the function; this uses a default argument so you can still call it in the same way.
The [... for line in f] is a list comprehension, which is like doing lst = []; for line in f: lst.append(...) but faster to write and to run.
Opening a file in 'w' mode allows you to write to it. Note that this will delete the already-existing contents of the file; you can use 'a' or 'w+' to avoid that, but that requires a little more work to reconcile the existing contents with your book list.
The * in read_bookfile splits a list up as if you passed them as separate arguments to a function.
'/'.join() takes the list of strings and joins them together using slashes: '/'.join(["a", "b", "c"]) is "a/b/c". It needs strings, though, which is why I did str(isbn) (because book.isbn is an int).
Python is "batteries included", remember?
Consider using the "csv" module:
use csv
csv.reader(...)
csv.writer(...)
I think these have lots of options (like you can set your delimiters to be other than commas; you can read in to a list of dictionaries, etc.)
See Python Docs for CSV reader/writer:
I have to make a few assumptions about your Book class, but I think this might help put you on the right track:
bookList = read_bookfile()
outfile = open("booklist.txt", "w")
for book in bookList:
bookStr = book.title + " " + book.firstname + " " + book.lastname + " " + book.isbn + " " + book.availability + " " + book.borrowed + " " + book.late + " " + book.returnday + "\n"
outfile.write(bookStr)
outfile.close()