I'm trying to create a code that will get the filename from the user input and print the contents in uppercase format. Below is my code:
filename = raw_input("Enter file name: ")
fh = open(filename)
for fx in fh:
fy = rstrip()
print(fy.upper)
The upper() and rstrip() functions do not change the string "in place", they return the modified string.
filename = raw_input("Enter file name: ")
fh = open(filename)
for line in fh:
line = line.rstrip()
line = line.upper()
print(line)
fh.close()
Of course all these can be strung together into a big unreadable line:
for line in fh:
print( line.rstrip().upper() )
Related
Every time I write a code I keep getting error. here is the code I have
def main():
outflow = open("studentList.txt", "r")
for line in outflile:
line[:-1].split(" ")
print(line)
main()
If your studentList file contain the name of the student one per each line so the way of reading is:
def main():
noOfStudents = 0
outflow = open("studentList.txt", "r")
for line in outflow:
noOfStudents+=1
print(line.rstrip("\n"))
print("Total no of students is :", noOfStudents)
outflow.close()
main()
Output:
student A
student B
student C
Total no of students is : 3
If students names are in line by line in the text file then use this
filename = "studentList.txt"
with open(filename) as f:
lines = f.read().splitlines()
print(lines)
or if students names are separated from space then use the following one
filename = "studentList.txt"
with open(filename, 'r') as f:
lines = f.read().encode("utf-8").replace(" ", "\n")
print(lines)
you do not have any outflile (probably a typo) difined this will raise NameError, so you can use:
def main():
outflow = open("studentList.txt", "r")
for line in outflow:
line[:-1].split(" ")
print(line)
main()
even better:
with open("studentList.txt", "r") as outflow:
for line in outflow:
line = line.rstrip().split(" ")
print(line)
I need current pointer just after my string is found. Below code not printing anything.
import requests
pname = input("Enter your product name:")
u = 'https://www.ebay.in/sch/i.html?_from=R40&_trksid=p2050601.m570.l1313.TR10.TRC0.A0.H0.Xhello.TRS0&_nkw='
url = u + pname + '&_sacat=0'
temp = []
r = requests.get(url)
with open("qwe.txt", "r+") as file:
file.write(str(r.content))
print(file.tell())
file.close()
with open("qwe.txt", "r") as file:
for line in file:
if 'lvpicinner full-width picW' in line:
break
print(file.tell())
file.seek(0)
Put break clause after print(file.tell()) and file.seek(0) like so:
for line in file:
if 'lvpicinner full-width picW' in line:
print(file.tell())
file.seek(0)
break
And if then nothing would print, then there is no such occurrences.
I have a file which contains a user:
Sep 15 04:34:31 li146-252 sshd[13326]: Failed password for invalid user ronda from 212.58.111.170 port 42579 ssh2
Trying to use index method for string to edit the user within the file. So far I am able to print the user but now to delete and put in the new user.
newuser = 'PeterB'
with open ('test.txt') as file:
for line in file.readlines():
lines = line.split()
string = ' '.join(lines)
print string.index('user')+1
Do you want to update the file contents? If so, you can update the user name, but you will need to rewrite the file, or write to a second file (for safety):
keyword = 'user'
newuser = 'PeterB'
with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
for line in infile.readlines():
words = line.split()
try:
index = words.index(keyword) + 1
words[index] = newuser
outfile.write('{}\n'.format(' '.join(words)))
except (ValueError, IndexError):
outfile.write(line) # no keyword, or keyword at end of line
Note that this code assumes that each word in the output file is to be separated by a single space.
Also note that this code does not drop lines that do not contain the keyword in them (as do other solutions).
If you want to preserve the original whitespace, regular expressions are very handy, and the resulting code is comparatively simple:
import re
keyword = 'user'
newuser = 'PeterB'
pattern = re.compile(r'({}\s+)(\S+)'.format(keyword))
with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
for line in infile:
outfile.write(pattern.sub(r'\1{}'.format(newuser), line))
If you want to change the names in your log, here is how.
file = open('tmp.txt', 'r')
new_file = []
for line in file.readlines(): # read the lines
line = (line.split(' '))
line[10] = 'vader' # edit the name
new_file.append(' '.join(line)) # store the changes to a variable
file = open('tmp.txt', 'w') # write the new log to file
[file.writelines(line) for line in new_file]
I need to omit all the information before '* START' and after '* END' in the txt file we open in Python(so the .txt is only the body)
We were given a string parameter and have written. it continues to write out the original .txt instead of just the body
def copy_file_2(s:str):
"that if its parameter is 'Gutenberg trim' it will copy only the body of a Project Gutenberg file, omitting the "housekeeping" material at the front and end. "
infile_name = input("Please enter the name of the file to copy: ")
infile = open(infile_name, 'r', errors = 'ignore')
outfile_name = input("Please enter the name of the new copy: ")
outfile = open(outfile_name, 'w')
if s == 'Gutenberg trim':
infile_data = infile.readlines()
for i in range(len(infile_data)):
t = '{:5d}: {}'.format(i+1,infile_data[i])
if "*** START" in t:
outfile.write(t)
else:
for line in infile:
outfile.write(line)
infile.close()
outfile.close()
print re.search("START(.*)END",open("some_file").read(),re.DOTALL).groups()[0]
Im pretty sure should work fine for you ...
I have two different functions in my program, one writes an output to a txt file (function A) and the other one reads it and should use it as an input (function B).
Function A works just fine (although i'm always open to suggestions on how i could improve).
It looks like this:
def createFile():
fileName = raw_input("Filename: ")
fileNameExt = fileName + ".txt" #to make sure a .txt extension is used
line1 = "1.1.1"
line2 = int(input("Enter line 2: ")
line3 = int(input("Enter line 3: ")
file = (fileNameExt, "w+")
file.write("%s\n%s\n%s" % (line1, line2, line3))
file.close()
return
This appears to work fine and will create a file like
1.1.1
123
456
Now, function B should use that file as an input. This is how far i've gotten so far:
def loadFile():
loadFileName = raw_input("Filename: ")
loadFile = open(loadFileName, "r")
line1 = loadFile.read(5)
That's where i'm stuck, i know how to use this first 5 characters but i need line 2 and 3 as variables too.
f = open('file.txt')
lines = f.readlines()
f.close()
lines is what you want
Other option:
f = open( "file.txt", "r" )
lines = []
for line in f:
lines.append(line)
f.close()
More read:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
from string import ascii_uppercase
my_data = dict(zip(ascii_uppercase,open("some_file_to_read.txt"))
print my_data["A"]
this will store them in a dictionary with lettters as keys ... if you really want to cram it into variables(note that in general this is a TERRIBLE idea) you can do
globals().update(my_data)
print A