I have a 2 programs that I've created. The first one writes a text file named celeb.txt file with a list of celebrity names that the user inputs. My second code reads that list and displays it.
The code works for both programs but I can not seem to get my formatting correct. I was the names to be listed vertical and not in a straight line. I don't want to combine the codes into 1 program either.
Ok so here is the first code that gets the user to end the names of celebrities:
import sys
def main():
myfile = open('celeb.txt', 'w')
celeb = input('Enter celebrity name or Enter to quit ')
if celeb:
myfile.write(str(celeb)+ '\n')
else:
sys.exit(0)
myfile.close()
print('File was created and closed')
main()
Here is my code that reads that .txt and outputs the names. I can't figure out how to list the name 1 on top of the other and not on 1 straight line.
def main():
myfile = open('celeb.txt', 'r')
line1 = myfile.readline()
myfile.close()
print(line1)
main()
If you want to take multiple names either take a name at a time:
def get_names(fle):
with open(fle,"a") as f:
while True:
inp = input("Enter a name or 'q' to quit :")
if inp == "q":
return
f.write("{}\n".format(inp))
def read_names(fle):
# open names file
with open(fle) as f:
# iterate over the file
# printing a name/line at a time
for name in f:
print(name)
Or if you are taking multiple names in one line get the user to separate the names and split before writing:
def get_names(fle):
with open(fle,"a") as f:
inp = input("Enter names separated by a space :")
f.writelines(("{}\n".format(n) for n in inp.split()))
def read_names(fle):
with open(fle) as f:
for name in f:
print(name)
Related
So basically I am making a program that writes the .txt file and changes the names in form by last to first like Woods, Tiger and turn them into usernames in this form twoods. They have to be formatted all in lower case and I think I messed up my code somewhere. Thanks!
The code I tried, below:
def main():
user_input = input("Please enter the file name: ")
user_file = open(user_input, 'r')
line = user_file.readlines()
line.split()
while line != '':
line = user_file.readline()
print(line.split()[-1][0][0:6]+line.split()[0][0:6]).lower() , end = '')
user_file.close()
if __name__ == "__main__":
main()
try this:
line = "Tiger Woods"
(fname, lname) = line.split(" ")
print(f'{fname[0:1]}{lname}'.lower())
There appear to be a couple of little issues preventing this from working / things that can be improved,
You are trying to split a list which is not possible. This is a string operation.
You are manually closing the file, this is not ideal
The program will not run as you are not using __name__ == "__main__"
Amended code,
def main():
user_input = input("Please enter the file name: ")
with open(user_input, 'r') as file_handler:
for line in file_handler:
print((line.split()[-1][0][0:6] + line.split()[0][0:6]).lower(), end='')
if __name__ == "__main__":
main()
If i understand your problem correctly, you want to read Surname,Name from a file line by line and turn them into nsurname formatted usernames.
For that, we can open and read the file to get user informations and split them line by line and strip the \n at the end.
After that, we can loop the lines that we read and create the usernames with given format and append them to an array of usernames.
Code:
# Get filename to read.
user_input = input("Please enter the file name: ")
# Open the given file and readlines.
# Split to lines and strip the \n at the end.
user_names = []
with open(user_input,'r') as user_file:
user_names = user_file.readlines()
user_names = [line.rstrip() for line in user_names]
print("User names from file: " + str(user_names))
# Loop the user informations that we read and split from file.
# Create formatted usernames and append to usernames list.
usernames = []
for line in user_names:
info = line.split(',')
username = (info[1][0:1] + info[0]).lower()
usernames.append(username)
print("Usernames after formatted: " + str(usernames))
Input File(test.txt):
Woods,Tiger
World,Hello
Output:
Please enter the file name: test.txt
User names from file: ['Woods,Tiger', 'World,Hello']
Usernames after formatted: ['twoods', 'hworld']
I am going through Intro to Programming so basic stuff here, I have an assignment to "write a program that asks a user for a file name and then displays the first 5 lines of the file," I just can't figure out how to use the input command in this situation and then transfer to open()
Edit: Sorry here is a code snippet I had, I just don't get how to apply input from here.
def main():
#This function writes to the testFile.docx file
outfile = open('testFile.docx', 'w')
outfile.write('Hello World\n')
outfile.write('It is raining outside\n')
outfile.write('Ashley is sick\n')
outfile.write('My dogs name is Bailey\n')
outfile.write('My cats name is Remi\n')
outfile.write('Spam Eggs and Spam\n')
outfile.close()
infile = open('testFile.docx', 'r')
testFileContent = infile.read()
infile.close()
print(testFileContent)
main()
First, we ask for a filename. Then we use the try clause, which checks whether the file exists. If it does it will print 5 lines. If it does not, it will print No such a file found!
x = input('Enter a file name')
try:
with open(x) as f:
data = f.readlines()
for i in range(5):
print(data[i])
except:
print('No such a file found!')
Using a simple function,
def hello_user():
user_input = input('Enter file name: ')
try:
with open(user_input, 'r') as f:
data = f.readlines()
data = data[:5]
for o in data:
print(o.strip())
except FileNotFoundError:
print('Not found ')
hello_user()
It asks for a file name
If the file exists in the same directory the script is running, it opens the file and read each lines (white lines inclusive)
We select only the first 5 lines
We iterate through the list and remove the extra whitespace character(e.g \n).
If the file was not found, we catch the exception.
input() is used to receive input from the user. Once we recieve the input, we use the open() method to read the file in read mode.
def main():
file = input("Please enter a file name")
with open(file, 'r') as f:
lines = f.readlines()
print(lines[:5])
The with statement makes sure that it closes the file automatically without explicitly calling f.close()
The method f.readlines() returns an array containing the lines in the file.
The print() statement prints the first 5 lines of the file.
I have a program that loops through the lines of a book to match some tags I've created indicating the start and the end of each chapter of this book. I want to separate each chapter into a different file. The program finds each chapter and asks the user to name the file, then it continues until the next chapter and so on. I don't know exactly where to put my "break" or something that could stop my loop. The program runs well but when it reaches the last chapter it goes back to the first chapter. I want to stop the loop and terminate the program when the tags and the chapters finish and also print something like "End of chapters". Can anyone help me with that? The code is below:
import re
def separate_files ():
with open('sample.txt') as file:
chapters = file.readlines()
pat=re.compile(r"[#introS\].[\#introEnd#]")
reg= list(filter(pat.match, chapters))
txt=' '
while True:
for i in chapters:
if i in reg:
print(i)
inp=input("write text a file? Y|N: ")
if inp =='Y':
txt=i
file_name=input('Name your file: ')
out_file=open(file_name,'w')
out_file.write(txt)
out_file.close()
print('text', inp, 'written to a file')
elif inp =='N':
break
else:
continue
else:
continue
separate_files()
I think a simpler definition would be
import re
def separate_files ():
pat = re.compile(r"[#introS\].[\#introEnd#]")
with open('sample.txt') as file:
for i in filter(pat.match, file):
print(i)
inp = input("write text to a file? Y|N: ")
if inp != "Y":
continue
file_name = input("Name of your file: ")
with open(file_name, "w") as out_file:
out_file.write(i)
print("text {} written to a file".format(i))
Continue the loop as soon as possible in each case, so that the following code doesn't need to be nested more and more deeply. Also, there's no apparent need to read the entire file into memory at once; just match each line against the pattern as it comes up.
You might also consider simply asking for a file name, treating a blank file name as declining to write the line to a file.
for i in filter(pat.match, file):
print(i)
file_name = input("Enter a file name to write to (or leave blank to continue: ")
if not file_name:
continue
with open(file_name, "w") as out_file:
out_file.write(i)
print("text {} written to {}".format(i, file_name)
I can't run your code but I assume if you remove the
while True:
line it should work fine. This will always be executed as there is nothing checked
For my assignment, I was given a text file named 'measles.txt' which contains A LOT of information, but most importantly, I'm focused on the year for each line. My task is to make a program that reads 'measles.txt', prompts the user for the year, and outputs every line with that year into another text file.
The problem that I can't figure out is that my professor specified that it has to work if the user inputs an incomplete year. For example, a line whose Year field contains “1987” would be selected by any of the following user responses: {“1”, “19”, “198”, “1987”}
Also, if the user inputs "","all", or "ALL", it has to output all the lines from the text file.
Here's measles.txt: https://bpaste.net/show/ade0a362b882
My current code is this:
input_file = open('measles.txt', 'r')
output_file_name = input("Please enter the name of the output file: ")
output_file = open(output_file_name, 'w')
for line in input_file:
output_file.write(line)
output_file.close()
input_file.close()
I found a much simpler answer. Since the year number in measles.txt is 88 characters from the beginning, I used that to create an if/elif statement.
input_file = open('measles.txt', 'r')
year = input("Please enter a year: ")
output_file_name = input("Please enter the name of the output file: ")
output_file = open(output_file_name, 'w')
# For loop that checks the end of the file for the year number
for line in input_file:
if year == line[88:88+len(year)]:
output_file.write(line)
elif year == ("", "all", "ALL"):
output_file.write(line)
output_file.close()
input_file.close()
Something like this might work. You can check whether a year starts with a certain string (for example '1' or '200'), this code below should return all the matching lines.
EDIT:
It seems like you found this code too complex but you made a mistake while copy/pasting and broke your solution. I modified your code to simplify it even more and fix it.
input_file = open('measles.txt', 'r')
year = input("Please enter a year: ")
output_file_name = input("Please enter the name of the output file: ")
output_file = open(output_file_name, 'w')
for line in input_file:
if year in ("", "all", "ALL") or line.split()[-1].startswith(year):
output_file.write(line)
output_file.close()
input_file.close()
I am learning Python as a beginner and have a question that I couldn't figure out. I need to write functions to allow users to setup/give a file a name and then enter contents.
The error message I got is: "Str' object is not callable. I don't know how to fix this. Please could you help me out. Many thanks!
The code is as follows:
=========================================
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
return fileName
#now to define a function for data entry
dataEntry = ""
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataFile = open(fName, APPEND(dataEntry))
fName.append(dataEntry)
return dataFile
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
while moreEntry != "N":
enterData() #here to call function to repeat data entry
fName.close()
fileName()
enterData()
print("Your file has been completed!")
fileContents = fName.readline()
print(fileContents)
I ran the code and... I seeing the error as line 14
14 dataFile = open(fName, APPEND(dataEntry))
APPEND appears to be a str. It does not appear to be a function.
fName is not declared in this scope. Your function spacing is off. Maybe you meant to run the all the code in order rather than in parts?
As it is, fName is declared and defined once globally (line 4), declared and defined in function filename() (line 6).
fName is also referred to in the function (line 7) Called unsuccessfully in line 14
dataFile = open(fName, APPEND(dataEntry)) # fName has not been declared in function enterData()
I suspect your code would work if you reordered your lines and not use functions (due to references) Also, please close your files. EG
f = open ("somefile.txt", "a+")
...
f.close() #all in the same block.
Thanks for all the inputs. Much appreciated. I've reworked the code a bit, and to put all data entry into a list first, then try to append the list to the file. It works, to a certain extent (about 80%, perhaps!)
However, I now have another problem. When I tried to open the file to append the list, it says "No such file or directory" next to the code (line31): "myFile = open(fName, APPEND)". But I thought I declared and then let user define the name at the beginning? How should I make it work, please?
Thanks in advance again!
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
fileName.close()
return fileName
#now to define a function for data entry
dataEntry = ""
dataList = []
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataList.append(dataEntry)
return
fileName()
enterData()
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
if moreEntry == "Y":
enterData()
else:
print("Your file has been completed successfully!")
myFile = open(fName, APPEND)
myFile.append(dataList)
myFile.close()
fileContents = fName.readline()
print(fileContents)