I'm reading from a .txt file that has one line of text (YPerson18) I'm wondering if there is a smarter way of writing this code preferably using a for loop.
import os
parent_dir = "../dirfiles"
os.chdir(parent_dir)
file_name = "userdata.txt"
append_mode = "a"
read_mode = "r"
read_file = open(file_name, read_mode)
the_lines = read_file.read(1)
print("Initial of the first name is: {}".format(the_lines))
the_lines = read_file.read(6)
print("The last name is: {}".format(the_lines))
the_lines = read_file.read(8)
print("The age is: {}".format(the_lines))
read_file.close()
How the output should look like:
Initial of the first name is: Y
The last name is: Person
The age is: 18
You could read the whole file into a string variable, then use slice notation to get parts of it.
with read_file = open(file_name, read_mode):
line = read_file.read().strip()
initial = line[0]
last_name = line[1:7]
age = int(line[7:])
Related
Good day everyone, How can i make this thing make TRUE? I already have existed .txt files but the outcome always False.
ID = input("Enter the name of your .txt file: ") +".txt" +"'"
IDS = "'" + ID
file_exists = os.path.exists(IDS)
print(file_exists)
print(IDS)
Get rid of ' before and after the file name:
ID = input("Enter the name of your .txt file: ") +".txt"
file_exists = os.path.exists(ID)
print(file_exists)
print(ID)
For example, if you had foo.txt and you put foo into your program, then your current code would look for a file named 'foo.txt', not foo.txt.
Try this:
#You may want to use str.strip() to get rid of unnecessary whitespaces
ID = input("Enter the name of your .txt file: ").strip() + ".txt"
file_exists = os.path.exists(ID)
print(f'{ID} exists') if file_exists else print(f'{ID} file does not exist')
Remove the quotes, you are adding single quotes to start and end of your string. Your code should look like this:
ID = input("Enter the name of your .txt file: ") +".txt"
file_exists = os.path.exists(ID)
print(file_exists)
print(IDS)
Quotes in programming languages indicate what are strings, and they are omitted by the interpreter when you output it into a terminal (print)
import os, re
config_file = "jsm_gyro_config.txt"
#fptr = open(config, "w")
#text = "demo text"
#fptr.write(text)
#fptr.close()
file = open(config_file, 'r')
file-read = file.read()
for line in file-read:
if re.search(userinput, file-read):
x = re.search(userinput, file-read)
# iteminputted is what the user wants to replace
iteminputted = "ref"
startpostion = x.span[1] + 3
endpostion = startposition + len(iteminputted)
# Find out how to write to a specific location in a file that will finish this off
else:
print("Item not found")
This is what i've tried and here is my thought process as always any help is appreatated and please make it understandable for an idiot :(
To begin with, you should not use - in your variable declarations as it is actually an operator and will always be treated as such. It will attempt to subtract.
Here is the same code with that fixed and also with the input
import os, re
config_file = "jsm_gyro_config.txt"
#fptr = open(config, "w")
#text = "demo text"
#fptr.write(text)
#fptr.close()
file = open(config_file, 'r')
file_read = file.read()
file.close() # You should always close your files.
for line in file_read:
if re.search(userinput, file_read):
x = re.search(userinput, file_read)
# iteminputted is what the user wants to replace
iteminputted = input("Input what you would like to replace > ")
startpostion = x.span[1] + 3
endpostion = startposition + len(iteminputted)
# Find out how to write to a specific location in a file that will finish this off
else:
print("Item not found")
However your question is very unclear, I did the best I could.
I am learning Python as a beginner and have a question that I couldn't figure out. I need to write functions to allow users to setup/give a file a name and then enter contents.
The error message I got is: "Str' object is not callable. I don't know how to fix this. Please could you help me out. Many thanks!
The code is as follows:
=========================================
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
return fileName
#now to define a function for data entry
dataEntry = ""
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataFile = open(fName, APPEND(dataEntry))
fName.append(dataEntry)
return dataFile
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
while moreEntry != "N":
enterData() #here to call function to repeat data entry
fName.close()
fileName()
enterData()
print("Your file has been completed!")
fileContents = fName.readline()
print(fileContents)
I ran the code and... I seeing the error as line 14
14 dataFile = open(fName, APPEND(dataEntry))
APPEND appears to be a str. It does not appear to be a function.
fName is not declared in this scope. Your function spacing is off. Maybe you meant to run the all the code in order rather than in parts?
As it is, fName is declared and defined once globally (line 4), declared and defined in function filename() (line 6).
fName is also referred to in the function (line 7) Called unsuccessfully in line 14
dataFile = open(fName, APPEND(dataEntry)) # fName has not been declared in function enterData()
I suspect your code would work if you reordered your lines and not use functions (due to references) Also, please close your files. EG
f = open ("somefile.txt", "a+")
...
f.close() #all in the same block.
Thanks for all the inputs. Much appreciated. I've reworked the code a bit, and to put all data entry into a list first, then try to append the list to the file. It works, to a certain extent (about 80%, perhaps!)
However, I now have another problem. When I tried to open the file to append the list, it says "No such file or directory" next to the code (line31): "myFile = open(fName, APPEND)". But I thought I declared and then let user define the name at the beginning? How should I make it work, please?
Thanks in advance again!
WRITE = "w"
APPEND = "a"
fName = ""
def fileName(): #to define name of the file.
fName = input("Please enter a name for your file: ")
fileName = open(fName, WRITE)
fileName.close()
return fileName
#now to define a function for data entry
dataEntry = ""
dataList = []
def enterData():
dataEntry = input("Please enter guest name and age, separated by a coma: ")
dataList.append(dataEntry)
return
fileName()
enterData()
#to determine if it's the end of data entry
moreEntry = input("Anymore guest: Y/N ")
if moreEntry == "Y":
enterData()
else:
print("Your file has been completed successfully!")
myFile = open(fName, APPEND)
myFile.append(dataList)
myFile.close()
fileContents = fName.readline()
print(fileContents)
Okay, so here's the deal, folks:
I've been experimenting with Python(3.3), trying to create a python program capable of generating random names for weapons in a game and replacing their old names, which are located inside a text file. Here's my function:
def ModifyFile(shareddottxt):
global name
a = open(str(shareddottxt) , 'r')
b = a.read()
namefix1 = '''SWEP.PrintName = "'''
namefix2 = '''" //sgaardname'''
name1 = b.find(namefix1) + len(namefix1)
name2 = b.find(namefix2, name1)
name = name + b[name1:name2] ## We got our weapon's name! Let's add the suffix.
c = open((shareddottxt + ".lua"), 'r+')
for line in b:
c.write(line.replace(name, (name + namesuffix)))
c.close()
a.close
As you can see, I first open my text file to find the weapon's name. After that, I try to create a new file and copy the contents from the old one, while replacing the weapon's name for (name + namesuffix). However, after calling the function, I get nothing. No file whatsoever. And even if I DO add the file to the folder manually, it does not change. At all.
Namesuffix is generated through another function early on. It is saved as a global var.
Also, my text file is huge, but the bit I'm trying to edit is:
SWEP.PrintName = "KI Stinger 9mm" //sgaardname
The expected result:
SWEP.PrintName = "KI Stinger 9mm NAMESUFFIX" //sgaardname
Where did I mess up, guys?
Something like this is more pythonic.
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r+') as file:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
file.seek(0)
file.write(new_lines)
If you don't want to replace that file
def replace_in_file(filename, oldtext, newtext):
with open(filename, 'r') as file, open(filename + ".temp", 'w') as temp:
lines = file.read()
new_lines = lines.replace(oldtext, newtext)
temp.write(new_lines)
Consider the following code:
import pickle
def open_file(fname, fname1 = None):
# returns a new OPEN file
if fname1:
while fname == fname1:
f_name = input("File already open, filename: ")
f = None
while not f:
try:
f = open(fname, "rb")
except IOError:
fname = input("File not found, filename: ")
print(fname, "open")
return f
def get_2cubes():
a_name = input("\nWhat is the name of the first cube's file? ")
a_file = open_file(a_name)
#a_cube = pickle.load(a_file)
a_file.close()
b_name = input("\nWhat is the name of the second cube's file? ")
b_file = open_file(b_name, a_name)
#b_cube = pickle.load(b_file)
b_file.close()
#return a_cube, b_cube
get_2cubes()
The code is meant to open a second file only if it's not the first file.
The first file's name is represented by fname1 in open_file(). If the name of the second file (b_name in this case) matches that of the first file the user will be prompted to enter a new name.
I supplied a default argument of None for the fname1 parameter because the function will sometimes be used only for opening one file and not for also comparing it to another file. However, I can't seem to override the default argument.
The a_name variable from the 7th line of get_2cubes is not being recognized by the if fname1: condition in open_file, and as a result I can open the same file twice. How would I correct this?
I think you need to use raw_input. Otherwise the text entered will treated as a variable name, and therefore will equal to None. (Unless you're on Python 3)