When I run,
Text = "Hello"
newFileName = (input("What would you like to name this file? "))
newFile = open(newFileName, 'w')
newFile.write(Text)
print("Saved as ", newFileName, "!")
It makes the file. However the file is empty. Does anyone know whats wrong here?
You have to close the file object newFile, otherwise the buffer that you are really writing to when you call newFile.write() might not get flushed to the actual file on disk. That is, add this line at the end:
newFile.close()
Python has a nice construct for dealing with this "setting up and tearing down" logic, known as context managers, used by the with statement. Using this, you can change your code to
Text = "Hello"
newFileName = input("What would you like to name this file? ")
with open(newFileName, 'w') as newFile:
newFile.write(Text)
print("Saved as ", newFileName, "!")
When the with block is done, the file is automatically closed, even if some error happens in the middle.
Related
i am trying to create a program that asks to the user what they want to do to a file read/append/delete the file.
FileName = open(input("Enter file name: "))
ReadFile = FileName.read()
Decision = input("Do you want to read/delete/append to the file?: ")
if Decision == "read":
print(ReadFile)
FileName.close()
elif Decision == "append":
Append = input("Type what you want to add: ")
with open("FileName","a") as file:
file.write(Append)
but when i check the file the it doesn't append it
This is happening because you're not actually opening the same file. You're asking the user for input to specify a file's location for reading that file, but should they choose to "append" the file, you have them append to a file that has nothing to do with the file they specified. You're having the user append a file called "FileName". You have hard coded that string as the file's location when the user chooses to "append".
Here, FileName is not a string representing the file's location. This is an object representing the file.
FileName = open(input("Enter file name: "))
You had the user enter a string to the file's path, but you didn't store that string value. You used that value to open() a file up for reading.
Here, you're opening a file called "FileName" in what is likely the directory python started in, since there's no path visible here.
with open("FileName","a") as file:
file.write(Append)
Go look in your starting directory and see if you've created a new file called "FileName".
Keep in mind, if you open a file with mode="a", and that file does not exist, a new file will be created.
https://docs.python.org/3/library/functions.html#open
I would also like to use this moment to inform you about PEP8, Python's styling guide. It's not law, but following it will help other Python programmers help you quicker.
With that said, consider making your code snippet look more like the following code:
filename = input("Enter file name: ")
decision = input("Do you want to read/delete/append to the file?: ")
if decision == "read":
with open(filename) as file:
print(file.read())
elif decision == "append":
append = input("Type what you want to add: ")
with open(filename, "a") as file:
file.write(append)
I am a beginner, learning programming using python 3.7. I am running a basic program to read content of a file after writing on it. But the print function won't print out the content of the file on the terminal. Can you please correct what mistake I am making here:
spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
x = work.read()
print(x)
work.close()
After the write() completes, the file's object index needs to be moved to the beginning of the file
add work.seek(0) before the read() operation
spam = input("What file would you like to open. Type the name below\n>>>")
# for the file name I type example.txt
work = open(spam, "r+")
work.write(input("Now write something on the file here\n>>"))
work.seek(0)
x = work.read()
print(x)
work.close()
You can't actually read your spam variable since it is not a file.
Instead:
work = open("NewFile.txt", "w")
work.write(spam)
work.close()
I've read every thing I can find and tried about 20 examples from SO and google, and nothing seems to work.
This should be very simple, but I cannot get it to work. I just want to point to a folder, and replace every double quote in every file in the folder. That is it. (And I don't know Python well at all, hence my issues.) I have no doubt that some of the scripts I've tried to retask must work, but my lack of Python skill is getting in the way. This is as close as I've gotten, and I get errors. If I don't get errors it seems to do nothing. Thanks.
import glob
import csv
mypath = glob.glob('\\C:\\csv\\*.csv')
for fname in mypath:
with open(mypath, "r") as infile, open("output.csv", "w") as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
writer.writerow(item.replace("""", "") for item in row)
You don't need to use csv-specific file opening and writing, I think that makes it more complex. How about this instead:
import os
mypath = r'\path\to\folder'
for file in os.listdir(mypath): # This will loop through every file in the folder
if '.csv' in file: # Check if it's a csv file
fpath = os.path.join(mypath, file)
fpath_out = fpath + '_output' # Create an output file with a similar name to the input file
with open(fpath) as infile
lines = infile.readlines() # Read all lines
with open(fpath_out, 'w') as outfile:
for line in lines: # One line at a time
outfile.write(line.replace('"', '')) # Remove each " and write the line
Let me know if this works, and respond with any error messages you may have.
I found the solution to this based on the original answer provided by u/Jeff. It was actually smart quotes (u'\u201d') to be exact, not straight quotes. That is why I could get nothing to work. That is a great way to spend like two days, now if you'll excuse me I have to go jump off the roof. But for posterity, here is what I used that worked. (And note - there is the left curving smart quote as well - that is u'\u201c'.
mypath = 'C:\\csv\\'
myoutputpath = 'C:\\csv\\output\\'
for file in os.listdir(mypath): # This will loop through every file in the folder
if '.csv' in file: # Check if it's a csv file
fpath = os.path.join(mypath, file)
fpath_out = os.path.join(myoutputpath, file) #+ '_output' # Create an output file with a similar name to the input file
with open(fpath) as infile:
lines = infile.readlines() # Read all lines
with open(fpath_out, 'w') as outfile:
for line in lines: # One line at a time
outfile.write(line.replace(u'\u201d', ''))# Remove each " and write the line
infile.close()
outfile.close()
When I run my code, there are no syntax errors, but it is not appending into the file. Basically, the user inputs their class and name (although this appears at the start of the program) and the program formulates a folder name and a file name - the file name being the user's name. The program then checks in the appropriate folder whether there is an existing file under the same name. If there isn't, the program creates a file in the correct folder and writes the user's score. The next time the same user runs the program, the file should be found. Python does output "File found", but the user's second score is not appended into the file. Any help on how to fix this?
All help is appreciated, thanks
Class_number = (input("Please enter your class: "))
score = (input("Please enter your score: "))
Folder = ("Class" + (Class_number))
File_name = (Name) + ".txt"
path = os.path.join("/Computing/a453/Task 3/",(Folder),(File_name))
if os.path.exists(path):
print("File found")
file = open((File_name), "a")
file.write((score) + "\n")
file.close()
else:
print("File not found. Creating file")
CompleteFile = os.path.join(Folder, File_name)
file = open(CompleteFile, "w")
file.write((score) + "\n")
file.close()
Short answer
You are checking if the file is present in a subfolder. If it is not present you create a new file in the desired folder and add the first score. If the file is present you are opening a different file! In the second case, the call to open just uses the filename without the folder (open(File_name, "a")) and not the whole path (open(CompleteFile, "w")).
Further Reading
Is there a special reason why you have to decide whether or not the file exists? Using open with mode a will create the file if it does not exist and append to it if it exists.
Note: open will not create missing folders for you!
Additionally, I would recommend to use Python's with statement (see this tutorial), as it will take care the file gets closed even if an exception is raised.
Combining everything said above your program would end up like this:
import os
name = "Test" # I had to come up with something
class_number = input("Please enter your class: ")
score = input("Please enter your score: ")
folder = "Class" + class_number
file_name = name + ".txt"
path = os.path.join(folder, file_name)
if os.path.exists(path):
print("File found")
else:
print("File not found. Creating file")
with open(path, "a") as txt_file:
txt_file.write(score + "\n")
In general, please check back with your Python reference. As someone told you in a comment, there are a lot of unnecessary parentheses and the style in naming your variables is not really consistent (have a look at Python's "official/recommended" naming conventions).
There are good online resources showing you the basics of Python. I personally enjoyed learning through Codecademy a lot (it's absolutely free).
So I am completely new to Python and can't figure out what's wrong with my code.
I need to write a program that asks for the name of the existing text file and then of the other one, that doesn't necessarily need to exist. The task of the program is to take content of the first file, convert it to upper-case letters and paste to the second file. Then it should return the number of symbols used in the file(s).
The code is:
file1 = input("The name of the first text file: ")
file2 = input("The name of the second file: ")
f = open(file1)
file1content = f.read()
f.close
f2 = open(file2, "w")
file2content = f2.write(file1content.upper())
f2.close
print("There is ", len(str(file2content)), "symbols in the second file.")
I created two text files to check whether Python performs the operations correctly. Turns out the length of the file(s) is incorrect as there were 18 symbols in my file(s) and Python showed there were 2.
Could you please help me with this one?
Issues I see with your code:
close is a method, so you need to use the () operator otherwise f.close does not do what your think.
It is usually preferred in any case to use the with form of opening a file -- then it is close automatically at the end.
the write method does not return anything, so file2content = f2.write(file1content.upper()) is None
There is no reason the read the entire file contents in; just loop over each line if it is a text file.
(Not tested) but I would write your program like this:
file1 = input("The name of the first text file: ")
file2 = input("The name of the second file: ")
chars=0
with open(file1) as f, open(file2, 'w') as f2:
for line in f:
f2.write(line.upper())
chars+=len(line)
print("There are ", chars, "symbols in the second file.")
input() does not do what you expect, use raw_input() instead.