So, I am creating an app that needs to make use of files in python. I watched 10000 youtube videos, and I got this from what I watched
with open(str(fileName)) as foil: # to read
notes = foil.read().splitlines()
with open("notes.txt", "a") as foil: # to add
print(toAdd, file=foil)
But when I do print(notes.splitlines()[0]), My program always prints an empty string.
I did a check to change it to something if it is blank
if notes.splitLines()[0] == "": notes = "The note was empty"
Why is this happening? Thanks in advance to anybody that awnsers.
PS: Where do these files go? Do I need to replace "notes.txt" with a file path for it to work?
PPS: There is no syntax errors in my program. If there is one in my code in this post, I simply got it wrong when typing it into this post.
Your code raises an exception (AttributeError) for me. In general, notes will be a list of the lines in your source file - if the source file is empty, this should also raise an error as the list index will be out of range.
In general, your filename needs to be the path that your program needs to find the file. If they are in the same directory, something like 'file.txt' will be enough. If not, you will have to provide the full path, or it will result in a FileNotFoundError. Hope this clears up your questions.
Related
I'm new to python, trying to learn and code at the same time, to test what i can do, I learned java, javascript, php, html, css, on my course, so I still remeber the basics.
I reached this problem and after hours i haven't found a solution that I can understand and like.
So this is my structure:
my structure
I want to read the test_input.txt inside the test_input.py, i want that because there are some strings for the user, and i want those strings to change based on the language. I though to write the .txt along side the .py file, but then everytime a function would generate string I would need to make all the language folders again, also if needed to add another language, I also would make various folders on every string occurency.
If possible, i want a solution that read the project inside itself to get the .txt file, because i want this project to be an .exe desktop program. Also, is pyhton good to make simple desktop apps? I'm lookin foward to learn the future languages, like I learned android in java, but I want to use kotlyn because is "better", so I cold make this project in java as a learned and did some in the past, but I want the "what will be most used on the future".
Please correct me in anything if I'm wrong, all this is more about see what I can do, and how, thanks for the help!!!
If I understand you correctly, you want to load and read the txt file in py. If this is the case, like i understood, then perhaps you want to follow this tutorial here:
https://www.pythontutorial.net/python-basics/python-read-text-file/
Also, did you try to open/load it already? If so, did you get an error? Most of the time, it is a path problem for beginners so make sure the path is setup already.
Cheers
I got this script from geeksforgeeks, it got multiple form of how to read a .txt, I am leaving you as well the documentation.
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
https://www.geeksforgeeks.org/reading-writing-text-files-python/
I was writing a python dictionary book1 as a csv to a file in another folder. I generally use PyCharm, but today I decided to go with th python shell for some reason.
My code was this:
with open(filepath, 'w+') as file:
for key in book1.keys():
file.write('%s,%s\n'%(key, book1[key]))
and the code worked as expected, with all the right data in the right places,
except in the console, it printed this seemingly random sequence of numbers:
73,88,98,89,86,86,90,92,102,94,92,104,92,90,94,94,88,86,90,90,88,88,113,103,109,107,105,106,73
I have been using Python for some time, but I have only ever seen this for the first time, and i am not sure what i am looking at. Screenshot image
Could Someone please enlighten me as to what those numbers might mean and why they never appeared in PyCharm?
You can find more info on this here:
https://docs.python.org/3/tutorial/inputoutput.html
f.write(string) writes the contents of string to the file, returning the number of characters written.
>>> f.write('This is a test\n')
15
I hope that I can ask this in a clear way, im very much a beginner to python and forums in general so I apologise if i've got anything wrong from the start!
My issue is that I am currently trying to use os.system() to enable a program to run on every file within a directory (this is a directory of ASCII tables which I am crossing with a series of other tables to find matches.
import os
for filename in os.listdir('.'):
os.system('stilts tmatch2 ifmt1=ascii ifmt2=ascii in1=intern in2= %s matcher=2d values1='col1 col2' values2='col1 col2' params=5 out= %s-table.fits'%(filename,filename))
So what im hoping this would do is for every 'filename' it would operate this program known as stilts. Im guessing this gets interrupted/doesn't work because of the presence of apostrophes ' in the line of code itself, which must disrupt the syntax? (please correct me if I am wrong)
I then replaced the ' in os.system() with "" instead. This, however, stops me using the %s notation to refer to filenames throughout the code (at least I am pretty sure anyway).
import os
for filename in os.listdir('.'):
os.system("stilts tmatch2 ifmt1=ascii ifmt2=ascii in1=intern in2= %s matcher=2d values1='col1 col2' values2='col1 col2' params=5 out= %s-table.fits"%(filename,filename))
This now runs but obviously doesn't work, as it inteferes with the %s input.
Any ideas how I can go about fixing this? are there any alternative ways to refer to all of the other files given by 'filename' without using %s?
Thanks in advance and again, sorry for my inexperience with both coding and using this forum!
I am not familiar with os.system() but maybe if you try do some changes about the string you are sending to that method before it could behave differently.
You must know that in python you can "sum" strings so you can save your commands in a variable and add the filenames as in:
os.system(commands+filename+othercommands+filename)
other problem that could be working is that when using:
for file in os.listdir()
you may be recievin file types instead of the strings of their names. Try using a method such as filename.name to check if this is a different type of thing.
Sorry I cant test my answers for you but the computer I am using is too slow for me to try downloading python.
It is a code to rename all the files in a given directory but it seems while running in my terminal it giving me a syntax error at the print statement. Also if I comment the statement I get an error at the if statement of main. If I remove that too I get an error at the rename_files() function call statement.
import os
def rename_files():
#Get all the files from directory
file_list = os.listdir("/Users/arpitgarg/test")
print file_list
#Rename all the files.
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789")
print file_name
if __name__ == '__main__':
rename_files()
I doubt the trace back error is 'can't find the file specified', if so your py script needs to know where the files to rename; cause its not in the current working directory.
You'll have to add:
os.chdir('the exact path to files to be renamed')
before the for loop
The file_names function does not contain a properly indented statement . Neither does the if name=='main' conditional. Also, the os.rename function call is missing a closing parenthesis . Try using a IDE next time , like pyCharm. It will highlight these syntax errors to you.
When asking for help, provide us with the necessary information to help.. in this case the actual Traceback.
As stated before, the indentation is one major error. Python uses whitespace to differentiate code blocks. http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Indentation
I recommend using PyCharm, as also stated before, but it is a memory hog. If running on an older computer, I would recommend using Notepad++ or PyScripter.
I have written a few lines of code in Python to see if I can make it read a text file, make a list out of it where the lines are lists themselves, and then turn everything back into a string and write it as output on a different file. This may sound silly, but the idea is to shuffle the items once they are listed, and I need to make sure I can do the reading and writing correctly first. This is the code:
import csv,StringIO
datalist = open('tmp/lista.txt', 'r')
leyendo = datalist.read()
separando = csv.reader(StringIO.StringIO(leyendo), delimiter = '\t')
macrolist = list(separando)
almosthere = ('\t'.join(i) for i in macrolist)
justonemore = list(almosthere)
arewedoneyet = '\n'.join(justonemore)
with open('tmp/randolista.txt', 'w') as newdoc:
newdoc.write(arewedoneyet)
newdoc.close()
datalist.close()
This seems to work just fine when I run it line by line on the interpreter, but when I save it as a separate Python script and run it (myscript.py) nothing happens. The output file is not even created. After having a look at similar issues raised here, I have introduced the 'with' parameter (before I opened the output file through output = open()), I have tried flushing as well as closing the file... Nothing seems to work. The standalone script does not seem to do much, but the code can't be too wrong if it works on the interpreter, right?
Thanks in advance!
P.S.: I'm new to Python and fairly new to programming, so I apologise if this is due to a shallow understanding of a basic issue.
Where are the input file and where do you want to save the output file. For this kind of scripts i think that it's better use absolute paths
Use:
open('/tmp/lista.txt', 'r')
instead of:
open('tmp/lista.txt', 'r')
I think that the error can be related to this
It may have something to do with where you start your interpreter.
Try use a absolute path /tmp/randolista.txt instead of relative path tmp/randolista.txt to isolate the problem.