Write command removing quotes and adding them at random - string

So I am programming in python 2.7 and I am trying to copy a text file line by line so that I can modify a few lines and save as a new file. I have everything working except the output file has a whole bunch of quotes(") removed and added? This is what one original line looks like:
"IECKAI" TurbModel - Turbulence model ("IECKAI"=Kaimal, "IECVKM"=von Karman, "GP_LLJ", "NWTCUP", "SMOOTH", "WF_UPW", "WF_07D", "WF_14D", "TIDAL", or "NONE")
When I run
f = open('C:\\Users\\bhansen\\Desktop\\TestEnv\\TurbSim2.inp', 'r')
NewInputFile = open('C:\\Users\\bhansen\\Desktop\\TestEnv\\MyInput.inp', 'wb')
for i in range(0, 66):
line = f.readline()
if i == 31:
num, stf = line.split(" ", 1)
num = '9'
new_line = num + stf
NewInputFile.write(new_line)
elif i == 36:
num, stf = line.split(' ', 1)
num = '8'
new_line = num + stf
NewInputFile.write(new_line)
else:
NewInputFile.write(line)
it gets written to the new file like this
"IECKAI TurbModel - Turbulence model ""(""""IECKAI""""=Kaimal,"" IECVKM=von Karman, GP_LLJ, NWTCUP, SMOOTH, WF_UPW, WF_07D, WF_14D, TIDAL, or NONE)"
Why is it going this and how do I fix it?
P.S. the given line was line 30 of the text file but it also does the same thing for the if statement lines

So I figured it out. After sending the source code and input file to someone else we found that for some reason (only this machine) didn't like reading from a .inp file. So we changed the read in file to a .txt file type but left the output file as a .inp (which it had to be for the program it was being passed to) and it worked just fine.

Related

How to edit a line in a notepad file using python

I am trying to edit a specific line of a notepad file using Python 3. I can read from any part of the file and write to the end of it, however whenever I have tried editing a specific line, I am given the error message 'TypeError: 'int' object is not subscriptable'. Does anybody know how I could fix this?
#(This was my first attempt)
f = open('NotepadTester.txt', 'w')
Edit = input('Enter corrected data')
Line = int(input('Which line do you want to edit?'))
f.write(Edit)[Line-1]
f.close()
main()
#(This was my second attempt)
f = open('NotepadTester.txt', 'w')
Line = int(input('Which line do you want to edit?'))
Edit = input('Enter corrected data')
f[Line-1] = (Edit)
main()
you can't directly 'edit' a line in a text file as far as I know. what you could do is read the source file src to a variable data line-by-line, edit the respective line and write the edited variable to another file (or overwrite the input file) dst.
EX:
# load information
with open(src, 'r') as fobj:
data = fobj.readlines() # list with one element for each text file line
# replace line with some new info at index ix
data[ix] = 'some new info\n'
# write updated information
with open(dst, 'w') as fobj:
fobj.writelines(data)
...or nice and short (thanks to Aivar Paalberg for the suggestion), overwriting the input file (using open with r+):
with open(src, 'r+') as fobj:
data = fobj.readlines()
data[ix] = 'some new info\n'
fobj.seek(0) # reset file pointer...
fobj.writelines(data)
You should probably load all the lines into memory first, modify it from there, and then write the whole thing to a file.
f = open('NotepadTester.txt', 'r')
lines = f.readlines()
f.close()
Which_Line = int(input('Which line do you want to edit? '))
Edit = input('Enter corrected data: ')
f = open("NotepadTester.txt",'w')
for i,line in enumerate(lines):
if i == Which_Line:
f.writelines(str(Edit)+"\n")
else:
f.writelines(line)
f.close()

Python coinflip code problem: How to delete lines in .text files?

So I'm tring to write a basic coinflip program that I will implement in a web i need the three .text files : heads, crowns and total to keep the overal values. Is there an algorithm or a module that lets u delete the privius content of the file?
(sorry for anything wrong with my question it is my first time asking in stack)
I tried runing the code and it works. My problem is that after it read and tries to write the new number the new number gets writen after the previous one. My only expirience with file handling was in c and in c if u write it makes a new file.
def main():
tot_num = open('total.txt', 'r+')
while True:
try:
x = input('Flip(F) or Exit(E)').lower()
except ValueError:
print('You had ur options try again')
else:
if x == 'f' or x == 'flip':
cf = coin_flip()
if cf == 'head':
print('Coin --> HEAD')
heads = open('heads.txt', 'r+')
h_num = int(heads.read())
heads.write(f'{h_num + 1}')
tn = int(tot_num.read())
tot_num.write(f'{tn + 1}')
heads.close()
show_coin_flip_num()
elif cf == 'crown':
print('Coin --> CROWN')
crowns = open('crown.txt', 'r+')
c_num = int(crowns.read())
crowns.write(f'{c_num + 1}')
tn = int(tot_num.read())
tot_num.write(f'{tn + 1}')
crowns.close()
show_coin_flip_num()
else:
break
else:
print('Exiting...')
break
The error is basically there cuz after the new number is added it goes next to the previous one it can read it normally the next time. It takes '012'
from the file.
Traceback (most recent call last):
File "file_path", line 462, in <module>
main()
File "file_path", line 442, in main
tn = int(tot_num.read())
ValueError: invalid literal for int() with base 10: ''
I made my program work but it is peculiar that there is not function to delete a specific line from file. I will try to make one myself and post it here because all the answers in
https://stackoverflow.com/q/4710067/7987118 are used to remove specific strings from a text file.

Replacing a float number in txt file

Firstly, I would like to say that I am newbie in Python.
I will ll try to explain my problem as best as I can.
The main aim of the code is to be able to read, modify and copy a txt file.
In order to do that I would like to split the problem up in three different steps.
1 - Copy the first N lines into a new txt file (CopyFile), exactly as they are in the original file (OrigFile)
2 - Access to a specific line where I want to change a float number for other. I want to append this line to CopyFile.
3 - Copy the rest of the OrigFile from line in point 2 to the end of the file.
At the moment I have been able to do step 1 with next code:
with open("OrigFile.txt") as myfile:
head = [next(myfile) for x iin range(10)] #read first 10 lines of txt file
copy = open("CopyFile.txt", "w") #create a txt file named CopyFile.txt
copy.write("".join(head)) #convert list into str
copy.close #close txt file
For the second step, my idea is to access directly to the txt line I am interested in and recognize the float number I would like to change. Code:
line11 = linecache.getline("OrigFile.txt", 11) #opening and accessing directly to line 11
FltNmb = re.findall("\d+\.\d+", line11) #regular expressions to identify float numbers
My problem comes when I need to change FltNmb for a new one, taking into consideration that I need to specify it inside the line11. How could I achieve that?
Open both files and write each line sequentially while incrementing line counter.
Condition for line 11 to replace the float number. Rest of the lines are written without modifications:
with open("CopyFile.txt", "w") as newfile:
with open("OrigFile.txt") as myfile:
linecounter = 1
for line in myfile:
if linecounter == 11:
newline = re.sub("^(\d+\.\d+)", "<new number>", line)
linecounter += 1
outfile.write(newline)
else:
newfile.write(line)
linecounter += 1

Find items in a text file that is a incantinated string of capitalized words that begin with a certain capital letter in python

I am trying to pull a string of input names that get saved to a text file. I need to pull them by capital letter which is input. I.E. the saved text file contains names DanielDanClark, and I need to pull the names that begin with D. I am stuck at this part
for i in range(num):
print("Name",i+1," >> Enter the name:")
n=input("")
names+=n
file=open("names.txt","w")
file.write(names)
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
quit()
else:
letter=input("Enter the first letter of the names you want to look up in uppercase:")
file=open("names.txt","r")
fileNames=[]
file.list()
for letter in file:
fileNames.index(letter)
fileNames.close()
I know that the last 4 lines are probably way wrong. It is what I tried in my last failed attempt
Lets break down your code block by block
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n=input("")
names+=n
I took the liberty of giving num a value of 5, and names a value of "", just so the code will run. This block has no problems. And will create a string called names with all the input taken. You might consider putting a delimiter in, which makes it more easier to read back your data. A suggestion would be to use \n which is a line break, so when you get to writing the file, you actually have one name on each line, example:
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n = input()
names += n + "\n"
Now you are going to write the file:
file=open("names.txt","w")
file.write(names)
In this block you forget to close the file, and a better way is to fully specify the pathname of the file, example:
file = open(r"c:\somedir\somesubdir\names.txt","w")
file.write(names)
file.close()
or even better using with:
with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
openfile.write(names)
The following block you are asking if the user want to lookup a name, and then exit:
lookUp=input("Did you want to look up any names?(Y/N)")
x= ord(lookUp)
if x == 110 or x == 78:
quit()
First thing is that you are using quit() which should not be used in production code, see answers here you really should use sys.exit() which means you need to import the sys module. You then proceed to get the numeric value of the answer being either N or n and you check this in a if statement. You do not have to do ord() you can use a string comparisson directly in your if statement. Example:
lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
sys.exit()
Then you proceed to lookup the requested data, in the else: block of previous if statement:
else:
letter=input("Enter the first letter of the names you want to look up in uppercase:")
file=open("names.txt","r")
fileNames=[]
file.list()
for letter in file:
fileNames.index(letter)
fileNames.close()
This is not really working properly either, so this is where the delimiter \n is coming in handy. When a text file is opened, you can use a for line in file block to enumerate through the file line by line, and with \n delimiter added in your first block, each line is a name. You also go wrong in the for letter in file block, it does not do what you think it should be doing. It actually returns each letter in the file, regardless of whay you type in the input earlier. Here is a working example:
letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
for line in openfile: ## loop thru the file line by line
line = line.strip('\n') ## get rid of the delimiter
if line[0].lower() == letter.lower(): ## compare the first (zero) character of the line
result.append(line) ## append to result
print(result) ## do something with the result
Putting it all together:
import sys
num = 5
names = ""
for i in range(num)
print("Name",i+1," >> Enter the name:")
n = input("")
names += n + "\n"
with open(r"c:\somedir\somesubdir\names.txt","w") as openfile:
openfile.write(names)
lookup = input("Did you want to look up any names?(Y/N)")
if lookup.lower() == "n":
sys.exit()
letter = input("Enter the first letter of the names you want to look up in uppercase:")
result = []
with open(r"c:\somedir\somesubdir\names.txt", "r") as openfile:
for line in openfile:
line = line.strip('\n')
if line[0].lower() == letter.lower():
result.append(line)
print(result)
One caveat I like to point out, when you create the file, you open the file in w mode, which will create a new file every time, therefore overwriting the a previous file. If you like to append to a file, you need to open it in a mode, which will append to an existing file, or create a new file when the file does not exist.

python3 opening files and reading lines

Can you explain what is going on in this code? I don't seem to understand
how you can open the file and read it line by line instead of all of the sentences at the same time in a for loop. Thanks
Let's say I have these sentences in a document file:
cat:dog:mice
cat1:dog1:mice1
cat2:dog2:mice2
cat3:dog3:mice3
Here is the code:
from sys import argv
filename = input("Please enter the name of a file: ")
f = open(filename,'r')
d1ct = dict()
print("Number of times each animal visited each station:")
print("Animal Id Station 1 Station 2")
for line in f:
if '\n' == line[-1]:
line = line[:-1]
(AnimalId, Timestamp, StationId,) = line.split(':')
key = (AnimalId,StationId,)
if key not in d1ct:
d1ct[key] = 0
d1ct[key] += 1
The magic is at:
for line in f:
if '\n' == line[-1]:
line = line[:-1]
Python file objects are special in that they can be iterated over in a for loop. On each iteration, it retrieves the next line of the file. Because it includes the last character in the line, which could be a newline, it's often useful to check and remove the last character.
As Moshe wrote, open file objects can be iterated. Only, they are not of the file type in Python 3.x (as they were in Python 2.x). If the file object is opened in text mode, then the unit of iteration is one text line including the \n.
You can use line = line.rstrip() to remove the \n plus the trailing withespaces.
If you want to read the content of the file at once (into a multiline string), you can use content = f.read().
There is a minor bug in the code. The open file should always be closed. I means to use f.close() after the for loop. Or you can wrap the open to the newer with construct that will close the file for you -- I suggest to get used to the later approach.

Resources