Fopen help

SpaceshipSpaceship
Watch

Alpha

Established Member
Impact
0
fopen

This is the BIGGEST part I struggle with. I don't know how to do it in ANY programming language. If someone could explain to me how I would write the phrase "This is a test" to a file and then output it to the screen I'd be VERY happy :) You can do it in PHP or Python, doesn't matter.
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
GoDaddyGoDaddy
Actually not all languages use fopen for opening files. Here's a few examples of the various methods different languages use. Each example opens file.txt for appending, writes a string to it, reopens the file for reading and outputs the content to the browser. If you want to overwrite the content of the file rather than append to it you can switch the "a" to "w" for both PHP and Python and change the ">>" to ">" for Perl.

PHP
Code:
<?
$file = fopen ("file.txt", "a");
fwrite ($file, "This is a PHP test<br />n");
fclose ($file);

$file = fopen ("file.txt", "r");
$lines = fread ($file, filesize ("file.txt"));
fclose ($file);
echo $lines;
?>

Python
Code:
#!/usr/bin/python

print "Content-type: text/htmlrnrn"

file = open('file.txt','a')
file.write("This is a Python test<br />n")
file.close()

file = open('file.txt','r')
for lines in file.readlines():
    print lines,
file.close()

Perl
Code:
#!/usr/bin/perl

print "Content-type: text/htmlnn";

open (FILE, ">>file.txt");
print FILE "This is a Perl test<br />n";
close (FILE);

open (FILE, "file.txt");
@lines = <FILE>;
close (FILE);
print @lines;
 
0
•••
Thanks very much! :) That will help me get it straight! BTW is it possible to create txt files with Python? So that if a txt file doesnt exist and you try to write to it it will be created?
 
0
•••
Yes Python will attempt to create the file if it doesn't exist when opened for appending or writing.
 
0
•••
Dynadot — .com TransferDynadot — .com Transfer
CatchedCatched

We're social

Escrow.com
Spaceship
Rexus Domain
CryptoExchange.com
Domain Recover
CatchDoms
DomDB
NameFit
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back