replace string with re in a file [duplicate] - python

This question already has answers here:
Re.sub not working for me
(2 answers)
Closed 3 years ago.
I want to quickly cancel out some unimportant strings in my file using the python module re.
I've tried it with other modules too, various loops and functions, but all I can get is to find the strings, not replace them with re.sub.
import re
chat = open("chat.txt"
chatText = chat.read()
def deleteMetaData():
for line in chatText:
re.sub("\[\d\d\.\d\d\.\d\d,\s\d\d:\d\d:\d\d\]\sGian\sDogwiler:\s", "", line)
deleteMetaData()
there are no error messages or whatsoever, just nothing. My goal is to cancel [20.07.18, 20:23:09] Gian Dogwiler: in every line of the file.

re.sub() doesn't automatically replace data in a file - you need to write it to the file as well. This answer provides a great example; I've modified it slightly to match your code. Note that you're also missing a close-paren on your chat = open("chat.txt" line.
import re
chat = open("chat.txt")
chatout = open("out.txt", "w")
def deleteMetaData():
for line in chat:
chatout.write(re.sub("\[\d\d\.\d\d\.\d\d,\s\d\d:\d\d:\d\d\]\sGian\sDogwiler:\s", "", line))
deleteMetaData()
chat.close()
chatout.close()
Don't forget to .close() your files when you're done with them.
Try it here!

Related

why python read informaton in file but not it's content? [duplicate]

This question already has an answer here:
Python Read File Content [duplicate]
(1 answer)
Closed 2 years ago.
I try to Python read and then print text from file score.txt (in score.txt is text hrllo world) i write this command:
score = open("data/score.txt", "r")
print(score)
and output is:
<_io.TextIOWrapper name='data/score.txt' mode='r' encoding='cp1250'>
how can i print "hello world" from file score.txt?
You probably want to read the whole filo into the variable in your case.
score = open("data/score.txt", "r").read()
See https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
I also offer some unsolicited advice: I recommend using a so-called context manager which will automatically close the file after you're done using it (even in case reading the file fails for some reason).
with open("data/score.txt", "r") as score_file:
print(score_file.read())
This is not really very important in your case, but it is an accepted best practice and should be followed whenever possible.

Python3 reading and writing .txt files [duplicate]

This question already has answers here:
What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?
(11 answers)
Closed 5 years ago.
I'm somewhat new to Python, but I have enough under my belt to know what I'm doing. What I'm trying to do is write a few lines for a .txt file (as well as a variable), and then print 5 of those characters.
import os
username = "Chad_Wigglybutt"
file = open("testfile.txt", "w")
file.write("Hello .txt file, ")
file.write("This is a test, ")
file.write("Can this write variables? ")
file.write("Lets see: ")
file.write(username)
file.close()
It then creates the file without issue, but when I add
print file.read(5)
to the code, it gives me a syntax error for file.read, and I have no clue why. I've been on the internet for a few hours now and I can't find anything. Either I'm extremely bad at google searching and I'm an idiot, or something's broken, or both. Any tips/ideas? :/
You're writing Python 3 code. In Python 3, print is a function, not a special statement. You need parentheses for function calls:
print(file.read(5))

"print file.read()" Invalid Syntax in Python 3 [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 7 years ago.
I wanted to create a 10 files where each file has a "blob" word at the first sentence and read those sentence directly.
Here's my code:
import random
import string
for i in range(9):
name = input('fileNumber')+ str(i+1) + '.txt'
try:
file = open(name,'w+')
file = open(name,'a')
file.write("blob")
file = open(name,'r')
print file.read() #'file' being highlighted with red color when I execute
file.close()
When I run it, I got an error message saying Invalid syntax and it highlights my file.read() line.
Can somebody tell me where's the flaw in my code?
EDIT: I'm currently using python 3.5. However, I could also switch to 2.7 as well!
Try doing this:
print(file.read())
In Python 3.x print() is a function and the parentheses are mandatory.

How to read text file with 1Ah char in it? [duplicate]

This question already has answers here:
Line reading chokes on 0x1A
(2 answers)
Closed 8 years ago.
I have a file, which is an assembly source with comments. These comments contain 1Ah character. It is a control character, the "substitute", but it also prints a nice right arrow in DOS, so someone long time ago thought it would be a shame not to use it.
Somehow, it works like end of file character for Python. All I do is:
f = open('file.asm')
for line in f:
print line
f.close()
And everything goes ok just until the first entrance of 1Ah.
The question is, how to read this symbol along with other text?
Open the file using universal line ending support:
f = open('file.asm', 'rU')
This avoids opening the file in native-platform text mode (in the C call) and prevents Windows from interpreting the \x1a code point as a line break.
Try:
f = open('file.asm', 'rb')
It should open file in binary mode.

Python read from command line arguments or stdin [duplicate]

This question already has answers here:
Read from File, or STDIN
(9 answers)
Closed 21 days ago.
When writing text-oriented command line programs in Python, I often want to read either all the files passed on the command line, or (XOR) standard input (like Unix cat does, or Perl's <>). So, I say
if len(args) == 0: # result from optparse
input = sys.stdin
else:
input = itertools.chain(*(open(a) for a in args))
Is this the Pythonic way of doing this, or did my miss some part of the library?
You need fileinput.
A standard use case is:
import fileinput
for line in fileinput.input():
process(line)
In Python 3, argparse handles filetype objects very nicely. It's an extremely powerful module and the docs come with many examples, so it's easy to quickly write the code you want. (How Pythonic!)
You may also benefit from this StackOverflow question about using argparse to optionally read from stdin.

Categories