I don't know how it works and can't see answer for this. I wanted to replace comma to dot in file. So i write this code:
with fileinput.FileInput("tabela.txt", inplace=True, backup='.bak') as file:
for line in file:
line = line.replace(',', '.')
and i thought it should work. But it didn't. But when i replace line=line.replace(...) to:
print(line.replace(",", "."), end='')
it works fine. Can someone explain why line=line.replace(...) doesn't work but print(...) which should just print something (and it even doesn't print lines) replace my comma to dots?
Thanks for answers
EDIT: I said that print should just print something, but ofc it's not true (i think) because as I can see it replace strings in my file in some reason with replace function.
From the docs
Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently).
So the library is built with the use-case of "get input in a variable and output to standard out" in mind. Hence, print is the intended mechanism.
Simply assigning to a local variable and then discarding the result does nothing. It replaces the string in memory and then... garbage collects it soon after. The real-world analogy would be doing a bunch of math homework on a sheet of paper and then putting the paper in the trash rather than submitting it; my teacher isn't going to grade what I throw away.
Related
I would like to know what this small portion of code means, because it seems like in the file that the script creates it adds a line in the end and i believe it might be one of those symbols
opened_file.write("%s\n" %user_input)
It writes a line. The content of user_input replaces the %s (see string interpolation in the docs) and \n is the newline character - after user_input.
Here is a good description of the different "inserting data into strings" methods, including % interpolation (which is now considered outdated):
https://realpython.com/python-string-formatting/
I have a file which currently stores a string eeb39d3e-dd4f-11e8-acf7-a6389e8e7978
which I am trying to pass into as a variable to my subprocess command.
My current code looks like this
with open(logfilnavn, 'r') as t:
test = t.readlines()
print(test)
But this prints ['eeb39d3e-dd4f-11e8-acf7-a6389e8e7978\n'] and I don't want the part with ['\n'] to be passed into my command, so i'm trying to remove them by using replace.
with open(logfilnavn, 'r') as t:
test = t.readlines()
removestrings = test.replace('[', '').replace('[', '').replace('\\', '').replace("'", '').replace('n', '')
print(removestrings)
I get an exception value saying this so how can I replace these with nothing and store them as a string for my subprocess command?
'list' object has no attribute 'replace'
so how can I replace these with nothing and store them as a string for my subprocess command?
readline() returns a list. Try print(test[0].strip())
You can read the whole file and split lines using str.splitlines:
test = t.read().splitlines()
Your test variable is a list, because readlines() returns a list of all lines read.
Since you said the file only contains this one line, you probably wish to perform the replace on only the first line that you read:
removestrings = test[0].replace('[', '').replace('[', '').replace('\\', '').replace("'", '').replace('n', '')
Where you went wrong...
file.readlines() in python returns an array (collection or grouping of the same variable type) of the lines in the file -- arrays in python are called lists. you, here are treating the list as a string. you must first target the string inside it, then apply that string-only function.
In this case however, this would not work as you are trying to change the way the python interpretter has displayed it for one to understand.
Further information...
In code it would not be a string - we just can't easily understand the stack, heap and memory addresses easily. The example below would work for any number of lines (but it will only print the first element) you will need to change that and
this may be useful...
you could perhaps make the variables globally available (so that other parts of the program can read them
more useless stuff
before they go out of scope - the word used to mean the points at which the interpreter (what runs the program) believes the variable is useful - so that it can remove it from memory, or in much larger programs only worry about the locality of variables e.g. when using for loops i is used a lot without scope there would need to be a different name for each variable in the whole project. scopes however get specialised (meaning that if a scope contains the re-declaration of a variable this would fail as it is already seen as being one. an easy way to understand this might be to think of them being branches and the connections between the tips of branches. they don't touch along with their variables.
solution?
e.g:
with open(logfilenavn, 'r') as file:
lines = file.readlines() # creates a list
# an in-line for loop that goes through each item and takes off the last character: \n - the newline character
#this will work with any number of lines
strippedLines = [line[:-1] for line in lines]
#or
strippedLines = [line.replace('\n', '') for line in lines]
#you can now print the string stored within the list
print(strippedLines[0]) # this prints the first element in the list
I hope this helped!
You get the error because readlines returns a list object. Since you mentioned in the comment that there is just one line in the file, its better to use readline() instead,
line = "" # so you can use it as a variable outside `with` scope,
with open("logfilnavn", 'r') as t:
line = t.readline()
print(line)
# output,
eeb39d3e-dd4f-11e8-acf7-a6389e8e7978
readlines will return a list of lines, and you can't use replace with a list.
If you really want to use readlines, you should know that it doesn't remove the newline character from the end, you'll have to do it yourself.
lines = [line.rstrip('\n') for line in t.readlines()]
But still, after removing the newline character yourself from the end of each line, you'll have a list of lines. And from the question, it looks like, you only have one line, you can just access first line lines[0].
Or you can just leave out readlines, and just use read, it'll read all of the contents from the file. And then just do rstrip.
contents = t.read().rstrip('\n')
I am quite new to Python3 and I have a hard time coding some stuff using python3.
I want to store the string characters into new variables which I read the new one using the readline() function in python3.
Below is my code with the input file description.
import sys
sys.stdin = open('../data/lecture.txt')
rl = lambda : (sys.stdin.readline().strip())
for _ in range(int(rl())):{
print(rl())
}
console
abbaaccb
dddcccbbbaaa
geegeegeegeebabybabybaby
oh
As you can see, I opened the lecture.txt and printed the values inside it using rl(). When I printed it, it showed the string characters as shown above.
However, when I specified the new variable and stored the characters into it, it throw error indicating syntax error as below
import sys
sys.stdin = open('../data/lecture.txt')
rl = lambda : (sys.stdin.readline().strip())
for _ in range(int(rl())):{
new_variable = str(rl().strip()) //where error occurred
}
I tried to google to resolve my issue but failed.
I attached the input file for your kindly help.
lecture.txt
4
abbaaccb
dddcccbbbaaa
geegeegeegeebabybabybaby
oh
Thanks
The reason for the SyntaxError is that Python doesn't use braces for blocks, it uses indentation.
Your original code sort of works, but in a very misleading way:
for _ in range(int(rl())):{
print(rl())
}
This looks like a compound block statement, but it's actually a single-line compound statement, where the statement controlled by the for is a set display being used as an expression statement, and of course the useless set {None} isn't there for any reason, it's just being evaluated for the side effect of calling print.
Your second version is trying to put an assignment statement inside a set display, which is illegal—statements can never go inside any kind of expression in Python.
If this is code you found somewhere, it was written as a joke, not as a foundation for you to build on or learn from. Almost everything it does is ridiculous:
You don't need to, or want to, reassign sys.stdin just to open a file.
You don't need to define a function just to read integers.
If you do want to define a named function in a statement, use def, not lambda.
There's no good reason to call strip() on a string you already stripped.
You don't need to strip off the whitespace anyway to call int; int('2\n') is already 2.
You don't need to call str on something that's already a string.
Obviously, you shouldn't wrap function calls with side effects inside a set display that creates a set you never use.
So, just throw it away and start over. Here's a more idiomatic way to do what that code is doing:
with open('../data/lecture.txt') as f:
count = int(f.readline())
for _ in range(count):
new_variable = f.readline().strip()
I'm writing a script that logs errors from another program and restarts the program where it left off when it encounters an error. For whatever reasons, the developers of this program didn't feel it necessary to put this functionality into their program by default.
Anyways, the program takes an input file, parses it, and creates an output file. The input file is in a specific format:
UI - 26474845
TI - the title (can be any number of lines)
AB - the abstract (can also be any number of lines)
When the program throws an error, it gives you the reference information you need to track the error - namely, the UI, which section (title or abstract), and the line number relative to the beginning of the title or abstract. I want to log the offending sentences from the input file with a function that takes the reference number and the file, finds the sentence, and logs it. The best way I could think of doing it involves moving forward through the file a specific number of times (namely, n times, where n is the line number relative to the beginning of the seciton). The way that seemed to make sense to do this is:
i = 1
while i <= lineNumber:
print original.readline()
i += 1
I don't see how this would make me lose data, but Python thinks it would, and says ValueError: Mixing iteration and read methods would lose data. Does anyone know how to do this properly?
You get the ValueError because your code probably has for line in original: in addition to original.readline(). An easy solution which fixes the problem without making your program slower or consume more memory is changing
for line in original:
...
to
while True:
line = original.readline()
if not line: break
...
Use for and enumerate.
Example:
for line_num, line in enumerate(file):
if line_num < cut_off:
print line
NOTE: This assumes you are already cleaning up your file handles, etc.
Also, the takewhile function could prove useful if you prefer a more functional flavor.
Assuming you need only one line, this could be of help
import itertools
def getline(fobj, line_no):
"Return a (1-based) line from a file object"
return itertools.islice(fobj, line_no-1, line_no).next() # 1-based!
>>> print getline(open("/etc/passwd", "r"), 4)
'adm:x:3:4:adm:/var/adm:/bin/false\n'
You might want to catch StopIteration errors (if the file has less lines).
Here's a version without the ugly while True pattern and without other modules:
for line in iter(original.readline, ''):
if …: # to the beginning of the title or abstract
for i in range(lineNumber):
print original.readline(),
break
I have a .txt file of words I want to 'clean' of swear words, so I have written a program which checks each position, one-by-one, of the word list, and if the word appears anywhere within the list of censorable words, it removes it with var.remove(arg). It's worked fine, and the list is clean, but it can't be written to any file.
wordlist is the clean list.
newlist = open("lists.txt", "w")
newlist.write(wordlist)
newlist.close()
This returns this error:
newlist.write(wordlist)
TypeError: expected a string or other character buffer object
I'm guessing this is because I'm trying to write to a file with a variable or a list, but there really is no alternate; there are 3526 items in the list.
Any ideas why it can't write to a file with a list variable?
Note: lists.txt does not exist, it is created by the write mode.
write writes a string. You can not write a list variable, because, even though to humans it is clear that it should be written with spaces or semicolons between words, computers do not have the free hand for such assumptions, and should be supplied with the exact data (byte wise) that you want to write.
So you need to convert this list to string - explicitly - and then write it into the file. For that goal,
newlist.write('\n'.join(wordlist))
would suffice (and provide a file where every line contains a single word).
For certain tasks, converting the list with str(wordlist) (which will return something like ['hi', 'there']) and writing it would work (and allow retrieving via eval methods), but this would be very expensive use of space considering long lists (adds about 4 bytes per word) and would probably take more time.
If you want a better formatting for structural data you can use built-in json module.
text_file.write(json.dumps(list_data, separators=(',\n', ':')))
The list will work as a python variable too. So you can even import this later.
So this could look something like this:
var_name = 'newlist'
with open(path, "r+", encoding='utf-8') as text_file:
text_file.write(f"{var_name} = [\n")
text_file.write(json.dumps(list_data, separators=(',\n', ':')))
text_file.write("\n]\n")