Okay so I'm trying to write a script that takes two files and modifies the first before writing it into the destination fine, but whenever I run it, the script only prints the first modified line over and over again.
#3a
def modify(string):
"""Takes a string and returns a modified version of the string using two modifications. One must be a replacement of some kind.
string -> string"""
while string != "":
string = string.upper()
string = string.replace("A","4").replace("B","8").replace("C","<").replace("E","3").replace("G","6").replace("I","1").replace("O","0").replace("R","|2").replace("S","5").replace("T","7").replace("Z","2")
print(string)
#3b - asks the user to type in a source code filename and destination filename; opens the files; loops through the contents of the source file line-by-line, using modify() to modify eat line before writing it to the destination file; the closes both files.
source = input("What file would you like to use?")
destination = input("Where would you like it to go?")
filesource = ""
while filesource == "":
try:
file_source = open(source, "r")
file_destination = open(destination, "w")
for item in file_source:
mod = modify(item)
file_destination.write(mod)
file_source.close()
file_destination.close()
break
except IOError:
source = input("I'm sorry, something went wrong. Give me the source file again please?")
Any help?
Hint: if you run modify("TEST ME") what does it return?
add return string to the end of the modify function.
The string never empties - try parsing through it char by char using an index int and your conditional being while i < len(string)
Related
I have a predefined function that I am currently running to check if a file a input is correct. I wish to open this file in my function with the with" operator. This is what I currently have:
def open_file():
'''Checks if the file is correct.'''
grab_file = True #Creates initial variable that checks if file is correct
while grab_file == True: #Loop initiates the check if true
txt = input("Enter a file name: ") #Asks for file input
try:
f = open(txt) #Tries to open the file
return f #File returned as output
grab_file = False #Stops the loop
except: #File is invalid, prompts for retry
print("Error. Please try again.")
def main():
'''Main function that runs through file and does delta calculations.'''
with open(open_file()) as f:
f.readline()
print_headers()
pass
Not sure what exactly is the issue, thanks! Note the second portion of the code is in its own main function and is not part of the open_file function.
The code gives me an error when I try to run the following:
f.readline()
date = f.readline()
print_headers()
This is the error I am getting, the code after the with open statement are just a simple readline(
"TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper"
Your error is a fairly easy fix:
just replace the
with open(open_file()) as f:
with
with open_file() as f:
because you've already opened the file and returned the open file in the open_file() function.
However the print_headers() function doesn't exist in standard python 3.x so I'm not quite sure if this is your own function or a different mistake.
def Delete_con():
contact_to_delete= input("choose name to delete from contact")
to_Delete=list(contact_to_delete)
with open("phonebook1.txt", "r+") as file:
content = file.read()
for line in content:
if not any(line in line for line in to_Delete):
content.write(line)
I get zero error. but the line is not deleted. This function ask the user what name he or she wants to delete from the text file.
This should help.
def Delete_con():
contact_to_delete= input("choose name to delete from contact")
contact_to_delete = contact_to_delete.lower() #Convert input to lower case
with open("phonebook1.txt", "r") as file:
content = file.readlines() #Read lines from text
content = [line for line in content if contact_to_delete not in line.lower()] #Check if user input is in line
with open("phonebook1.txt", "w") as file: #Write back content to text
file.writelines(content)
Assuming that:
you want the user to supply just the name, and not the full 'name:number' pair
your phonebook stores one name:number pair per line
I'd do something like this:
import os
from tempfile import NamedTemporaryFile
def delete_contact():
contact_name = input('Choose name to delete: ')
# You probably want to pass path in as an argument
path = 'phonebook1.txt'
base_dir = os.path.dirname(path)
with open(path) as phonebook, \
NamedTemporaryFile(mode='w+', dir=base_dir, delete=False) as tmp:
for line in phonebook:
# rsplit instead of split supports names containing ':'
# if numbers can also contain ':' you need something smarter
name, number = line.rsplit(':', 1)
if name != contact_name:
tmp.write(line)
os.replace(tmp.name, path)
Using a tempfile like this means that if something goes wrong while processing the file you aren't left with a half-written phonebook, you'll still have the original file unchanged. You're also not reading the entire file into memory with this approach.
os.replace() is Python 3.3+ only, if you're using something older you can use os.rename() as long as you're not using Windows.
Here's the tempfile documentation. In this case, you can think of NamedTemporaryFile(mode='w+', dir=base_dir, delete=False) as something like open('tmpfile.txt', mode='w+'). NamedTemporaryFile saves you from having to find a unique name for your tempfile (so that you don't overwrite an existing file). The dir argument creates the tempfile in the same directory as phonebook1.txt which is a good idea because os.replace() can fail when operating across two different filesystems.
I am a novice with Python I suppose, and I was wondering if there was a way to read a file and then check if user's input equalled that file's text.
I've been trying to create a password program without having to show the password/variable in the program. If there's another way to do this without doing .read() and things (if they don't work) then I would be happy to hear those suggestions!
This should do it:
# The path to the file
filepath = 'thefile.txt'
# This is how you should open files
with open(filepath, 'r') as f:
# Get the entire contents of the file
file_contents = f.read()
# Remove any whitespace at the end, e.g. a newline
file_contents = file_contents.strip()
# Get the user's input
user_input = input('Enter input: ')
if user_input == file_contents:
print('Match!')
else:
print('No match.')
I have the following code, which modifies each line of the file test.tex by making a regular expression substitution.
import re
import fileinput
regex=re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
for line in fileinput.input('test.tex',inplace=1):
print regex.sub(r'\3\2\1\4\5',line),
The only problem is that I only want the substitution to apply to certain lines in the file, and there's no way to define a pattern to select the correct lines. So, I want to display each line and prompt the user at the command line, asking whether to make the substitution at the current line. If the user enters "y", the substitution is made. If the user simply enters nothing, the substitution is not made.
The problem, of course, is that by using the code inplace=1 I've effectively redirected stdout to the opened file. So there's no way to show output (e.g. asking whether to make the substitution) to the command line that doesn't get sent to the file.
Any ideas?
The file input module is really for dealing with more than one input file.
You can use the regular open() function instead.
Something like this should work.
By reading the file then resetting the pointer with seek(), we can override the file instead of appending to the end, and so edit the file in-place
import re
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
with open('test.tex', 'r+') as f:
old = f.readlines() # Pull the file contents to a list
f.seek(0) # Jump to start, so we overwrite instead of appending
for line in old:
s = raw_input(line)
if s == 'y':
f.write(regex.sub(r'\3\2\1\4\5',line))
else:
f.write(line)
http://docs.python.org/tutorial/inputoutput.html
Based on the help everyone provided, here's what I ended up going with:
#!/usr/bin/python
import re
import sys
import os
# regular expression
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
# name of input and output files
if len(sys.argv)==1:
print 'No file specified. Exiting.'
sys.exit()
ifilename = sys.argv[1]
ofilename = ifilename+'.MODIFIED'
# read input file
ifile = open(ifilename)
lines = ifile.readlines()
ofile = open(ofilename,'w')
# prompt to make substitutions wherever a regex match occurs
for line in lines:
match = regex.search(line)
if match is not None:
print ''
print '***CANDIDATE FOR SUBSTITUTION***'
print '--: '+line,
print '++: '+regex.sub(r'\3\2\1\4\5',line),
print '********************************'
input = raw_input('Make subsitution (enter y for yes)? ')
if input == 'y':
ofile.write(regex.sub(r'\3\2\1\4\5',line))
else:
ofile.write(line)
else:
ofile.write(line)
# replace original file with modified file
os.remove(ifilename)
os.rename(ofilename, ifilename)
Thanks a lot!
How would you scan a dir for a text file and read the text file by date modified, print it to screen having the script scan the directory every 5 seconds for a newer file creadted and prints it.
Is it possible that you can help me i'm stuck and i need this real bad and i've already got the scan dir for file and print but it does not print the files by date modidfied.
import os,sys
os.chdir(raw_input('dir_path: ') )
contents=os.listdir('.') #contents of the current directory
files =[]
directory=[]
Time = time.ctime(os.path.getmtime(contents))
for i in contents:
if os.path.isfile(i) == True :
files.append(i)
elif os.path.isdir(i) == True :
directory.append(i)
#printing contents
choice = ""
for j in files:
while choice != "quit":
choice = raw_input("Dou you want to print file %s (y/n): "%j)
if choice == 'y':
print "**************************"
print "Printing Files %s" %j
print "**************************"
fileobj = open(j,'r')
contents = fileobj.readlines()
for k in contents:
sys.stderr.write(k)
else:
pass
what i wanted is instead of my code asking if it wants to print i need it to print the files if modified by the current time meaning if it read a file that was just placed in the directory and a new one comes in it will read the new file without prompting me.
the error it's giving me is coercing to unicode: need string or buffer, list found.
Repeating actions on a timer
You can repeat an action every five seconds by combining an infinite loop with the time.sleep() function, like so:
import time
while True:
time.sleep(5) # wait five seconds
print (time.time()) # print the time
Remember to have some kind of break condition in here if you need it, otherwise the loop will run forever.
"TypeError: coercing to Unicode: need string or buffer, list found"
Your problem is in the line
Time = time.ctime(os.path.getmtime(contents))
You have provided a list of filenames. The os.path.getmtime function expects one filename at a time. The error message is telling you that it has no idea how to convert a list of filenames into a filename.