name = input("Whats your name?: ")
Can I use for example my .txt that is in the same directory on the input 'name'?
I tried the code bellow /
with open(name.txt, "r") as file:
file.readlines()
But its not working :(
It's a bit unclear what you want exactly. I think you want the variable name to be a name taken from a textfile.
with open("name.txt", "r") as file:
name = file.readline().strip()
print(name)
It works by opening up the file name.txt for reading as text, then it reads the first line, strip() is used to remove any spaces or newlines, and it is stored in the variable name.
There is no need to call input().
Be sure to read the tutorial on input and output.
Related
Instructions:
If we don't know how many items are in a file, we can use read() to load the entire file and then use the line endings (the \n bits) to split it into lines. Here is an example of how to use split()
source = 'aaa,bbb,ccc'
things = source.split(',') # split at every comma
print(things) # displays ['aaa', 'bbb', 'ccc'] because things is a list
Task
Ask the user to enter names and keep asking until they enter nothing.
Add each new name to a file called names.txt as they are entered.
Hint: Open the file before the loop and close it after the loop
Once they have stopped entering names, load the file contents, split it into individual lines and print the lines one by one with -= before the name and =- after it.
Assuming you already have the file of names called input.txt like so:
Tom
Dick
Harry
Then the code to read the entire file, split on '\n' and print each name in the required format is
# Open the file
with open("input.txt") as file:
# Read the entire file
content = file.read()
# Split the content up into individual names
names = content.split('\n')
# Print the required string for each name
for name in names:
print(f'-={name}=-')
Hope that solves your problem.
So I have a script that I was building to replace words in a very large config file that I am rebuilding and renaming. So I will give an example of what it is that is going on. Lets say in the server line of the load balancer config I have "web01" and want to change it to "web01_svr", it works fine. But on the "add service" line I might have "web01-80-HTTP_sg". The script is inserting itself to make it "web01_svr-80-HTTP_sg". How do I specify in this script to only match exact objects and not partial?
with open('massiveconfig.txt', 'r') as file :
filedata = file.read()
Replace the target string
while True:
old = input("What is the old name you would like to replace?: ")
new = input("What is the new name you would like to replace the old
with?: ")
filedata = filedata.replace(old, new)
cont = input("Would you like to replace another?: Y/n")
# Write the file out again
with open('massiveconfig.txt', 'w') as file:
file.write(filedata)
Regex to the rescue:
import re
filedata = re.sub(r'\b'+ old +r'\b(?![-])', new, filedata)
You are not very specific, which special characters might be present in your words. I assume, _ or . are to be expected. In this case, you can adapt the script and use [-_.] instead of [-]
I'm new at programming and i need help with converting first file to another file. The task is:
Write a program that asks the user for two filenames. The first one should mark any existing text file. The second filename may be new, so the file with this name may not exist.
The program's task is to take the first file of the file, convert it to capital letters, and write another file.
So far I have:
file_old = input("Which file do you want to take ? ")
file_new = input("In which file do you want to put the content? ")
file1 = open(file_old, encoding="UTF-8")
file2 = open(file_new, "w")
for rida in file1:
file2.write(rida.upper())
file1.close()
file2.close()
You have to write the full path to your file for your code to work.
I tested it and it works perfectly.
The input path should be like
C:\Users\yourUserName\PycharmProjects\test_folder\test_small_letters.txt
This should be instead of old.txt that you enter
for example:
"C:\Program Files\Python36\python.exe" C:/Users/userName/PycharmProjects/pythonSnakegame/test_file_capitalize.py
which file you want to take ? C:\Users\userName\PycharmProjects\test_folder\test_small_letters.txt
In which file you want to put the content? C:\Users\userName\PycharmProjects\test_folder\test_big_letters.txt
C:\Users\userName\PycharmProjects\test_folder\test_small_letters.txt
C:\Users\userName\PycharmProjects\test_folder\test_big_letters.txt
Process finished with exit code 0
The new file was created and capitalized.
You can do that in a more pythonic way, with the with statement. This creates a context manager which takes care to close() the file when you are done with it.
file_old = input("Which file do you want to take ? ")
file_new = input("In which file do you want to put the content? ")
with open(file_old, 'r') as f1:
with open(file_new, 'w') as f2:
for line in f1:
f2.write(line)
This question already has answers here:
Python error message io.UnsupportedOperation: not readable
(5 answers)
Closed 6 months ago.
I am working on a problem that says to make a program that gets a user input for a file and then within the file removes a string that the user specifies. I'm not sure how to go from what I have(below) to what the question asks for. As always any and all help is greatly appreciated.
def main():
outfile = open(input("Enter a file name: "), "a")
string = input("Enter the string to be removed: ")
for string in outfile.readlines():
string = string.replace(string, "")
outfile.close()
print("Done")
main()
I took one of the suggestions and tried to get it to work but as I said in my comment below the code below does not return an error it creates an empty file. What am I missing to get the new file to be the old file with the string removed?
def main():
inpath = input("Enter an input file: ")
line = input("Enter what you want to remove: ")
outpath = input("Enter an output file: ")
with open(inpath, "r") as infile, open(outpath, "w") as outfile:
for line in infile:
outfile.write(line.replace(line, "") + "\n")
print("Done.")
main()
A few side notes before getting into the details: When you call string.replace(string, ""), you're telling the string to replace its entire self with the empty string—you might as well just do string = "". Presumably the first string is the search string to replace, so give it a different name, and then use it as, e.g., string.replace(searchString, ""). Also, you don't want to name a variable string, because it's the name of a standard library module. You're calling your input file "outfile", which is apt to be confusing. You probably want to use a with statement instead of an explicit close. Finally, you can iterate the lines in a file with just for line in f:; you don't need for line in f.readlines() (and, if you ever need to deal with Python 2.x, you'll be much happier avoiding readlines(), because it will read the entire file into memory, and then make a huge list of lines in memory).
The first problem, as JBernardo pointed out, is that you've opened the file in "a" mode, which means "write-only, appending to the end". You can use "a+" or "r+" if you want to read and write.
However, that won't really help you. After all, you can't write to the file in the middle of reading it.
There are a few common ways around this.
First, just write to standard output, and let the user do whatever he wants with the results—e.g., redirect it to a file. (In that case, you have print your prompt, "Done" message, etc. to standard error instead, so they don't get redirected to the file.) This is what many Unix tools like sed or sort do, so it's appropriate if you're building a Unix-style tool, but may not be right for other purposes.
def stderrinput(prompt):
sys.stderr.write(prompt)
sys.stderr.flush()
return input()
def main():
with open(stderrinput("Enter a file name: "), "r") as infile:
searchString = stderrinput("Enter the string to be removed: ")
for line in infile:
print(infile.replace(searchString, ""))
sys.stderr.write("Done\n")
Second, write to another file. Open the input file in "r" mode, and the output file in "w", mode, and then you're just copying lines:
def main():
inpath = input("Enter an input file: ")
outpath = input("Enter an output file: ")
with open(inpath, "r") as infile, open("outpath", "w") as outfile:
for line in infile:
outfile.write(line.replace(searchString, "") + "\n")
Third, read and process the whole file in memory, then truncate and rewrite the whole file:
def main():
path = input("Enter an input/output file: ")
with open(path, "r+") as inoutfile:
lines = [line.replace(searchString, "") for line in inoutfile]
inoutfile.seek(0)
inoutfile.truncate()
inoutfile.writelines(lines)
Finally, write to a temporary file (as with the second option), then move that temporary file on top of the original input file. Something like this:
def main():
path = input("Enter an input/output file: ")
with open(path, "r") as infile, tempfile.NamedTemporaryFile("w", delete=False) as outfile:
for line in infile:
outfile.write(line.replace(searchString, ""))
shutil.move(outfile.name, pathname)
This last one is a little tricky, because of the differences between POSIX and Windows. However, it has some big advantages. (For example, if your program gets killed in the middle of operation, no matter how it happens, you're guaranteed to have either the original file or the new file, not some half-written mess.)
The Problem - Update:
I could get the script to print out but had a hard time trying to figure out a way to put the stdout into a file instead of on a screen. the below script worked on printing results to the screen. I posted the solution right after this code, scroll to the [ solution ] at the bottom.
First post:
I'm using Python 2.7.3. I am trying to extract the last words of a text file after the colon (:) and write them into another txt file. So far I am able to print the results on the screen and it works perfectly, but when I try to write the results to a new file it gives me str has no attribute write/writeline. Here it the code snippet:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess
x = raw_input("Enter the full path + file name + file extension you wish to use: ")
def ripple(x):
with open(x) as file:
for line in file:
for word in line.split():
if ':' in word:
try:
print word.split(':')[-1]
except (IndexError):
pass
ripple(x)
The code above works perfectly when printing to the screen. However I have spent hours reading Python's documentation and can't seem to find a way to have the results written to a file. I know how to open a file and write to it with writeline, readline, etc, but it doesn't seem to work with strings.
Any suggestions on how to achieve this?
PS: I didn't add the code that caused the write error, because I figured this would be easier to look at.
End of First Post
The Solution - Update:
Managed to get python to extract and save it into another file with the code below.
The Code:
inputFile = open ('c:/folder/Thefile.txt', 'r')
outputFile = open ('c:/folder/ExtractedFile.txt', 'w')
tempStore = outputFile
for line in inputFile:
for word in line.split():
if ':' in word:
splitting = word.split(':')[-1]
tempStore.writelines(splitting +'\n')
print splitting
inputFile.close()
outputFile.close()
Update:
checkout droogans code over mine, it was more efficient.
Try this:
with open('workfile', 'w') as f:
f.write(word.split(':')[-1] + '\n')
If you really want to use the print method, you can:
from __future__ import print_function
print("hi there", file=f)
according to Correct way to write line to file in Python. You should add the __future__ import if you are using python 2, if you are using python 3 it's already there.
I think your question is good, and when you're done, you should head over to code review and get your code looked at for other things I've noticed:
# the txt file I'm trying to extract last words from and write strings into a file
#Hello:there:buddy
#How:areyou:doing
#I:amFine:thanks
#thats:good:I:guess
First off, thanks for putting example file contents at the top of your question.
x = raw_input("Enter the full path + file name + file extension you wish to use: ")
I don't think this part is neccessary. You can just create a better parameter for ripple than x. I think file_loc is a pretty standard one.
def ripple(x):
with open(x) as file:
With open, you are able to mark the operation happening to the file. I also like to name my file object according to its job. In other words, with open(file_loc, 'r') as r: reminds me that r.foo is going to be my file that is being read from.
for line in file:
for word in line.split():
if ':' in word:
First off, your for word in line.split() statement does nothing but put the "Hello:there:buddy" string into a list: ["Hello:there:buddy"]. A better idea would be to pass split an argument, which does more or less what you're trying to do here. For example, "Hello:there:buddy".split(":") would output ['Hello', 'there', 'buddy'], making your search for colons an accomplished task.
try:
print word.split(':')[-1]
except (IndexError):
pass
Another advantage is that you won't need to check for an IndexError, since you'll have, at least, an empty string, which when split, comes back as an empty string. In other words, it'll write nothing for that line.
ripple(x)
For ripple(x), you would instead call ripple('/home/user/sometext.txt').
So, try looking over this, and explore code review. There's a guy named Winston who does really awesome work with Python and self-described newbies. I always pick up new tricks from that guy.
Here is my take on it, re-written out:
import os #for renaming the output file
def ripple(file_loc='/typical/location/while/developing.txt'):
outfile = "output.".join(os.path.basename(file_loc).split('.'))
with open(outfile, 'w') as w:
lines = open(file_loc, 'r').readlines() #everything is one giant list
w.write('\n'.join([line.split(':')[-1] for line in lines]))
ripple()
Try breaking this down, line by line, and changing things around. It's pretty condensed, but once you pick up comprehensions and using lists, it'll be more natural to read code this way.
You are trying to call .write() on a string object.
You either got your arguments mixed up (you'll need to call fileobject.write(yourdata), not yourdata.write(fileobject)) or you accidentally re-used the same variable for both your open destination file object and storing a string.